Home  >  Article  >  Backend Development  >  How to convert the data returned by childNodes into a dimensional array

How to convert the data returned by childNodes into a dimensional array

一个新手
一个新手Original
2017-10-09 09:35:131408browse


//将childNodes返回的数据转化为数组的方法
            function convertToArray(nodes){
                var array=null;
                try{
                    array=Array.prototype.slice.call(nodes,0);
                }catch(ex){
                    array=new Array();
                    for(var i=0,len=nodes.length;i<len;i++){
                        array.push(nodes[i]);
                    }
                }
                return array;
            }
            //筛选节点的方法
            function getElementList(arr,value){
                var arrList=new Array();
                for(var i=0,len=arr.length;i<len;i++){
                    if(arr[i].nodeType==value){
                        arrList.push(arr[i]);
                    }
                }
                return arrList;
            }

Each node has a childNodes attribute, which stores the NodeList object. NodeList is an array-like object used to store an ordered set of nodes that can be accessed by position. However, everyone needs to pay attention to the fact that although we can access the object through square brackets, and NodeList also has the length attribute, it is not an instance of Array.

Of course, we can also access the nodes in the NodeList through the item() method, just like using square brackets. There's nothing wrong with either way, and square brackets are preferred by developers because of their simplicity.

Here, the author still recommends the above method of converting NodeList to array, but because the method Array.prototypr.slice.call(soneNode.childNodes,0); is not supported in IE8 and below, so we NodeList can only be converted into a dimensional array through enumeration. try-catch catches the error and creates the array manually.

The above is the detailed content of How to convert the data returned by childNodes into a dimensional array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn