In this code I get the number of children of all li elements. 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
.
Depending on if you want the number of actual elements vs nodes to be greater than 1, you should swap childNodes
for children
. childNodes
will include any node, while children
only contains Elements
. See this question for a little bit more detail: What is the difference between children and childNodes in JavaScript?
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
2- Iterate through them and check the number of children
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]
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;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.