How to get all the li in the ul of the specified index
I want to write like this
var afterUl=document.querySelectorAll('ul')[sy-1];
var afterLi=afterUl.querySelectorAll('li');
But the following line will Error
leilei.html:128 Uncaught TypeError: Cannot read property 'querySelectorAll' of undefined. . .
How should I write. . Newbie help
----- 06-03 14:50 -----
Thanks to jasonintju for pointing out the error.
The error reported here is not because there is no
querySelectorAll
method, but because the subscript of the subject is out of bounds, resulting inundefined
,undefined
There is noquerySelectorAll
method, so an error is reported.There is no problem with correct subscript writing.
Supplementary documentation
Element.querySelectorAll() - Web APIs | MDN
----- 06-03 04:30 -----
leilei.html:128 Uncaught TypeError: Cannot read property 'querySelectorAll' of undefined
The error message has already reminded you that the
querySelectorAll
attribute cannot be read because it is undefinedThe reason is because
querySelectorAll
is a method ofdocument
, not a method ofelement
.The solution is to use
getElementsByTagName
You can refer to the introduction of these two APIs in the JavaScript documentation
Document.querySelectorAll - Web API Interface | MDN
element.getElementsByTagName - Web API Interface | MDN
Or use jQuery
There are many ways to implement it. You can use native JavaScript or various js libraries to implement it.
Here we use native JavaScript to organize an idea, add an id attribute to the DOM element of ul, remove the ul through document.getElementById, and then remove the li element through getElementsByTagName.
The code is as follows:
let oLis = document.getElementsByTagName("ul")[index].getElementsByTagName("li");
I found the error myself, because the variable sy in my subsequent index [sy-1] was assigned when traversing all li before. Because all li are much more than all ul, so [sy-1] exceeds ul. number, the upper line will be undefined and the lower line will report an error.
Thank you everyone. . This question is too childish. .