[英]How to get element who has more than one child?
In this code I get the number of children of all li elements. 在这段代码中,我得到了所有li元素的子代数。 But how can I get li element who has more than one child? 但是我怎样才能得到一个孩子以上的李元素呢?
let liLength = document.querySelectorAll('li').length; for (let i = 0; i < liLength; i++) { let liChildrenLength = document.querySelectorAll('li')[i].children.length; console.log(liChildrenLength); }
<body> <ul> <li><a>list</a></li> <li><a>list</a> <ul> <li><a>list</a></li> <li><a>list</a></li> </ul> </li> <li><a>list</a> <ul> <li><a>list</a></li> <li><a>list</a></li> </ul> </li> </ul> <script src="main.js"></script> </body>
Convert the NodeList
to an Array
and use filter
and childNodes
. 将NodeList
转换为Array
并使用filter
和childNodes
。
Depending on if you want the number of actual elements vs nodes to be greater than 1, you should swap childNodes
for children
. 根据您是否希望实际元素与节点的数量大于1,应将childNodes
换为children
。 childNodes
will include any node, while children
only contains Elements
. childNodes
将包含任何节点,而children
节点仅包含Elements
。 See this question for a little bit more detail: What is the difference between children and childNodes in JavaScript? 有关更多细节,请参见此问题:JavaScript中的child和childNodes有什么区别?
const arr = Array.from(document.querySelectorAll('li')).filter(li => li.childNodes.length > 1); console.log(arr);
<body> <ul> <li><a>list</a></li> <li><a>list</a> <ul> <li><a>list</a></li> <li><a>list</a></li> </ul> </li> <li><a>list</a> <ul> <li><a>list</a></li> <li><a>list</a></li> </ul> </li> </ul> </body>
1- Store all li
s in array instead of length 1-将所有li
而不是长度存储在数组中
2- Iterate through them and check the number of children 2-遍历他们并检查孩子的数量
Something like this 像这样
let lis = document.querySelectorAll('li'); for (let i = 0; i < lis.length; i++) { if (lis[i].children.length > 1) { console.log(lis[i].children) console.log('------------------') } }
<body> <ul> <li><a>list</a></li> <li><a>list</a> <ul> <li><a>list</a></li> <li><a>list</a></li> </ul> </li> <li><a>list</a> <ul> <li><a>list</a></li> <li><a>list</a></li> </ul> </li> </ul> <script src="main.js"></script> </body>
var liLength = document.querySelectorAll('li').length; for (var i = 0; i < liLength; i++) { var liChildren = document.querySelectorAll('li')[i].children; if (liChildren.length > 1) for (var j = 0; j < liChildren.length; j++) console.log(liChildren[j]); }
<body> <ul> <li><a>list</a></li> <li><a>list</a> <ul> <li><a>list</a></li> <li><a>list</a></li> </ul> </li> <li><a>list</a> <ul> <li><a>list</a></li> <li><a>list</a></li> </ul> </li> </ul> <script src="main.js"></script> </body>
Same as parsing through an array use [indexNumber]
与通过数组进行解析相同,使用[indexNumber]
liChildren = document.querySelectorAll('li')[i].children;
liChildren[someIndex]
Hope that was the question 希望这是问题
try this: 尝试这个:
let li = [...document.querySelectorAll('li')].filter(function(li) {
return li.children.length;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.