You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 an HTMLCollection with document.getElementsByTagName('li').
  • Inside the loop, you reassign bodyd to Array.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 innerText values 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:29:15