Changing the order of elements

前端 未结 4 1172
耶瑟儿~
耶瑟儿~ 2020-11-30 12:16

I am creating a website of floating width. The users use screens from full HD resolution to some 600px on smart phones it seems a pretty good idea. This brings up a very int

4条回答
  •  甜味超标
    2020-11-30 13:14

    For this simple case (swapping the only two elements), you can just use appendChild():

    (() => {
      const list = document.querySelector("ul");
      list.appendChild(list.firstElementChild);
    })();
    • List-item #1
    • List-item #2

    The same node cannot exist in multiple positions; so, it's removed from its current position and placed at the end of the collection.

    If you want to do more complicated sorting, you probably ought to create an array from the childNodes and get all crazy:

    (() => {
      const frag = document.createDocumentFragment();
      const list = document.querySelector("ul");
      const items = list.querySelectorAll("li");
      const sortedList = Array.from(items).sort(function(a, b) {
        const c = a.textContent,
          d = b.textContent;
        return c < d ? -1 : c > d ? 1 : 0;
      });
      for (let item of sortedList) {
        frag.appendChild(item);
      }
      list.appendChild(frag);
    })();
    • Dogs
    • Snakes
    • Cats
    • Bugs

提交回复
热议问题