Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move the first four list items to the end of the list

So I have a list with several <li> elements,

<ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
    <li>f</li>
    <li>g</li>
    <li>h</li>
</ul>

The context is I want to re-use li elements across a 1,000 memory intensive list for iOS. The objective is to display first 4 elements, the rest 4 are hidden, the container displays 4 items at a time.

On scroll (button tap), I'm going to animate the list and slide in the other 4, and at the end of the animation, move the first 4 li items towards the end of the list (and then reset the position to left: 0 for the ul)

My question is how I can get a hold of first elements and add them towards the end in plain javascript. (I'm handling animation through TweenLite)

Bonus: if you can suggest some better optimization techniques or library when it comes to display numerous elements.


2 Answers

Here's how you can do it in pure JS. You can access the li elements with getElementsByTagName() and use slice() to get the first 4. Then you can add them to the ul by popping them from the array with shift() and putting them on the end with appendChild()

Working JSFiddle here.

function moveEle() {
    var ele = document.getElementsByTagName("li");
    //getElementsByTagName() returns a collection, so we bind the slice function to it
    var fourEle = Array.prototype.slice.call( ele, 0, 4);
    var ul = document.getElementsByTagName("ul")[0];

    while (fourEle.length > 0) {
        //Pop the first element from the 4 and add it to the end
        ul.appendChild(fourEle.shift());
    }
}

document.getElementById("clickMe").onclick = moveEle;

Edit: To add an element at the beginning, use insertBefore() instead of appendChild(). You'd also use pop() instead of shift() in the above example.

like image 113
Parker Avatar answered Nov 20 '25 20:11

Parker


You can get a NodeList to iterate through by using getElementsByTagName(), like this:

var list = document.getElementById("yourUlItem").getElementsByTagName("li");

You can then use Array slice function to catch all the subsets you need by preserving the right index in order to catch the sets :

var firstFour = list.slice(0, 3);
like image 40
KAD Avatar answered Nov 20 '25 19:11

KAD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!