DOM HTML的数组方法?

时间:2018-01-17 12:49:34

标签: javascript html arrays dom

我需要从array代码制作li。数组必须包含其内部texts。 Eache索引在数组中,每个内部textsli标记。

我试图通过Array.prototype.slice()调用数组方法切片。但可能是我做错了......

结果必须如下:

arr = ["Animals", "0_", .... , "fish__"]



var bodyd = document.getElementsByTagName('li');
for (var i = 0; i < bodyd.length; i++) {
  bodyd = Array.prototype.slice.call(bodyd, 1);
  console.log(bodyd);
}
&#13;
<ul>
  <li>Animals
    <ul>
      <li>0_
        <ul>
          <li>1__</li>
          <li>2__</li>
          <li>3__</li>
          <li>4__</li>
        </ul>
      </li>
      <li>Other_
        <ul>
          <li>Slis__</li>
          <li>Bird__</li>
          <li>Repti__</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Fish
    <ul>
      <li>Aqua
        <ul>
          <li>Aqua__</li>
          <li>Aqua__</li>
        </ul>
      </li>
      <li>fish_
        <ul>
          <li>fish__</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

试试这个

var bodyd = document.getElementsByTagName('li');

bodyd = Array.prototype.slice.call(bodyd).map(function(val) {
    return val.firstChild.data.trim();
});

console.log(bodyd);