如何用Array方法从DOM的li标签提取文本生成数组?调用slice遇问题
How to Extract All
<li> innerText into an Array Let's fix this up for you! The issue with your current code is that you're modifying the bodyd variable inside the loop, which completely breaks the iteration logic. Here's a breakdown of the problem and the correct solutions:
What's Wrong with Your Current Code?
- You start by getting all
<li>elements as anHTMLCollectionwithdocument.getElementsByTagName('li'). - Inside the loop, you reassign
bodydtoArray.prototype.slice.call(bodyd, 1), which removes the first element from the collection/array each time. This means your loop's length check (i < bodyd.length) keeps changing, leading to skipped elements and incorrect results. - You're not actually collecting the
innerTextvalues anywhere—you're just logging the modified collection.
Correct Solutions
Solution 1: Use Array.from() (Modern Approach)
This method directly converts the HTMLCollection to an array and maps each <li> to its innerText (we'll use trim() to clean up extra newlines/spaces from nested lists):
// Get all li elements const allLis = document.getElementsByTagName('li'); // Convert to array and extract trimmed innerText const arr = Array.from(allLis, li => li.innerText.trim()); console.log(arr);
Solution 2: Use slice() + map() (Legacy Browser Support)
If you need to support older browsers that don't have Array.from(), convert the HTMLCollection to an array first with slice(), then map to get the text:
const allLis = document.getElementsByTagName('li'); // Convert HTMLCollection to a regular array const lisArray = Array.prototype.slice.call(allLis); // Extract innerText for each li const arr = lisArray.map(li => li.innerText.trim()); console.log(arr);
Expected Result
For your provided HTML structure, the resulting array will be:
["Animals", "0_", "1__", "2__", "3__", "4__", "Other_", "Slis__", "Bird__", "Repti__", "Fish", "Aqua", "Aqua__", "Aqua__", "fish_", "fish__"]
内容的提问来源于stack exchange,提问作者Sviat Kuzhelev
相关产品推荐
相关产品推荐

