How to add an item to the top of a dynamic list

Like heading states, does anyone have the ability to implement this type of function?

Example: If you go to http://weewar.com , on your first page you will notice the ajax module, which is updated every second. However, all new items are added to the top of the list. My question is about the same functionality.

Does anyone have an easy and clear idea on how to implement this functionality?

So far, I have a method that initially creates a list, then another method is called in an interval that retrieves the most recent data from the server.

However, I'm stuck on how to add a new dynamic node to the top of the list.

If you can direct me to where I can find this information or give me an idea of ​​how I can implement this, I will be very happy and grateful :)

Thanks for the advanced.

+4
source share
3 answers

If you use jQuery, you can use jQuery('#list_ID:first-child').prepend(new_item);

If you want to do it the old way, document.getElementById('list_ID').innerHTML = new_item + document.getElementById('list_ID').innerHTML;

Or you can use a more convenient method for the DOM:

var list_item = document.createElement('li'); list_item.innerHTML="Some Text" document.getElementById('list_ID').insertBefore(list_item, document.getElementById('list_ID').firstChild);

+2
source

jQuery will make this pretty easy for you. Here is an example:

JQuery

 $(document).ready(function(){ $('<div>News 1</div>').prependTo('#textbox'); $('<div>News 2</div>').prependTo('#textbox'); $('<div>News 3</div>').prependTo('#textbox'); $('<div>News 4</div>').prependTo('#textbox'); }); 

HTML

 <div id="textbox"></div> 

Exit

 News 4 News 3 News 2 News 1 

As you can see, the news that was added for the first time is pushed down.

+7
source

One way is to recreate the list using javascript. This is similar to list.items = newitem + list.items. Sorry for writing conceptual pseudocode. If you need to know the exact javascript, send me an answer / comment.

You can also implement the same as follows:

 var m =document.getElementById(listElement).options.length; for(var i = m; i>= 0 ; i = i-1) document.getElementById(cmbCategory).options[i] = document.getElementById(cmbCategory).options[i-1]; var opt2 = new Option(); opt2.value="100"; /*new value */ opt2.text="New option text"; document.getElementById(listElement).options[document.getElementById(listElement).options.length] = opt2; 
0
source

Source: https://habr.com/ru/post/1312683/


All Articles