当前位置:网站首页>How does native JS get the child elements of the parent element that the current element belongs to

How does native JS get the child elements of the parent element that the current element belongs to

2022-06-23 02:57:00 It workers

Include text and comment nodes

Native JS There is a common trick that is through the elements of previousSibling attribute , An additional note is that this property will traverse text node , Enter key .

From scratch, we can obtain the number of child elements of an element that belong to the parent element through such code .

var child = this;
while( (child = child.previousSibling) != null ) 
    i++;

The case code is as follows :

Html:

<ul id="ul"><li>123</li><li id="a">a</li><li>b</li><li>c</li></ul>

JS:

var child = document.getElementById("a");
var i = 0;
while((child = child.previousSibling) != null) i++;
console.log(i) //console 1

Through the loop traversal previousSibling Whether the property is null This little trick , You can get the position of the current element in the parent element .

Does not contain text nodes and comment nodes

The implementation code is as follows :

var child = document.getElementById("a");
var parent = child.parentNode;
var index = Array.prototype.indexOf.call(parent,child);
console.log(index)//1
原网站

版权声明
本文为[It workers]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201261219134622.html