Get all LI elements in array

后端 未结 3 468
礼貌的吻别
礼貌的吻别 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: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; }

提交回复
热议问题