The method of JS native sequence to achieve a list of child elements reversed Analysis

This article describes how to implement native JS reverse the order of the list of child elements, analyzes javascript turned over the relevant operating skills for the dom element array reverse method, innerHTML methods, with examples in the form of a list of elements of the order, need friends can refer to
this article example describes a method to achieve JS native sequence listing child elements reversed. Share to you for your reference, as follows:

Write a function to a list of all the child elements inside the order is reversed, the problem is not difficult but there are a variety of solutions, but also big performance is not the same, here are some commonly used methods:

1. Using direct DOM operations:

var ul = document.getElementById('target');
var list = ul.getElementByTagName('li');
var length = list.length;
while(length--){
  ul.appendchild(ul.childNodes[length]);
}

This method is likely to affect the performance of the number of pages child element is relatively small sometimes, but when a large number of child elements when the page's performance will be greatly affected, because every time you insert page elements to direct DOM operation, and therefore do not recommend this approach.

2. Documentation in debris fragment method

var ul = document.getElementById('target');
var list = ul.getElementByTagName('li');
var fragment = document.createDocumentFragment();
for(var i = list.length; i >= 0; i--){
  fragment.appendChild(list[i]);
}
ul.appendChile(fragment);

Document fragments using the method of operation, the entire insertion process only the fragment had a DOM manipulation, no matter how much the child number of elements, compared to the first method, the page performance will be greatly improved, practical applications can use this methods.

Official fragment documentation https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment.

3. The method of using the reverse of the array

var ul = document.getElementById('target');
var chil_arr = Array.prototype.slice.call(ul.getElementByTagName('li'), 0);//因为getElementByTagName获取到的是伪数组,所以要进行转换
var str = '';
chil_arr.reverse();
for(var i = 0; i < chil_arr.length; i++){
  str += chil_arr[i].outerHTML;
}
ul.innerHTML(str);

This method is better performance.

4. The method of using innerHTML

var ul = document.getElementById('target');
var list = ul.getElementByTageName('li');
var str = "";
for(var i = list.length; i >= 0; i--){
  str += "<li>" + list[i].innerHTML + "</li>";
}
ul.innerHTML(str);

This method is the best performance, we recommend using this method in practical applications to improve the performance of the page.

Guess you like

Origin www.cnblogs.com/nayek/p/12498077.html