Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

javascript - Get all LI elements in array

How can i make JS select every LI element inside a UL tag and put them into an array?

<div id="navbar">
    <ul>
        <li id="navbar-One">One</li>
        <li id="navbar-Two">Two</li>
        <li id="navbar-Three">Three</li>
        <li id="navbar-Four">Four</li>
        <li id="navbar-Five">Five</li>
    </ul>
</div>

Can i make it so JS gets each of them into an array eg navbar['0'] would return document.getElementById("navbar-One")?

question from:https://stackoverflow.com/questions/4019894/get-all-li-elements-in-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get a NodeList to iterate through by using getElementsByTagName(), like this:

var lis = document.getElementById("navbar").getElementsByTagName("li");

You can test it out here. This is a NodeList not an array, but it does have a .length and you can iterate over it like an array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...