Get all LI elements in array

后端 未结 3 436
礼貌的吻别
礼貌的吻别 2020-12-05 13:03

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

相关标签:
3条回答
  • 2020-12-05 13:48

    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.

    0 讨论(0)
  • 2020-12-05 13:53

    After some years have passed, you can do that now with ES6 Array.from (or spread syntax):

    const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));
    console.log('Get first: ', navbar[0].textContent);
    
    // If you need to iterate once over all these nodes, you can use the callback function:
    console.log('Iterate with Array.from callback argument:');
    Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))
    
    // ... or a for...of loop:
    console.log('Iterate with for...of:');
    for (const li of document.querySelectorAll('#navbar>ul>li')) {
        console.log(li.textContent);
    }
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <div id="navbar">
      <ul>
        <li id="navbar-One">One</li>
        <li id="navbar-Two">Two</li>
        <li id="navbar-Three">Three</li>
      </ul>
    </div>

    0 讨论(0)
  • 2020-12-05 13:53

    QuerySelectorAll will get all the matching elements with defined selector. Here on the example I've used element's name(li tag) to get all of the li present inside the div with navbar element.

        let navbar = document
          .getElementById("navbar")
          .querySelectorAll('li');
    
        navbar.forEach((item, index) => {
          console.log({ index, item })
        });
       
    <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>

    0 讨论(0)
提交回复
热议问题