3

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.

Parker
  • 8,539
  • 10
  • 69
  • 98

2 Answers2

2

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.

Parker
  • 8,539
  • 10
  • 69
  • 98
1

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);
KAD
  • 10,972
  • 4
  • 31
  • 73
  • please add some more code to remove them from the list and add towards the end using plain javascript (no jquery) –  Aug 25 '15 at 17:57