0

I need to make an array from li tags. The array must include their inner texts. Eache index in array with each inner texts of li tags.

I'm trying to call the array method slice by Array.prototype.slice(). But probably I making some wrong...

The result must be like:

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);
}
<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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Sviat Kuzhelev
  • 1,758
  • 10
  • 28
  • 1
    What will be the desired output of the above?? Have you considered jQuery? Plain JS, loop over `document.querySelectorAll("li")` or nested loop over `document.querySelectorAll("ul")` – mplungjan Jan 17 '18 at 12:51
  • Yes, I know about `querySelectorAll` , but I want to make it by array methods. – Sviat Kuzhelev Jan 17 '18 at 12:53
  • 1
    I created a snippet for you. It was not clear you actually had tried something – mplungjan Jan 17 '18 at 12:53

1 Answers1

2

try this

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

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

console.log(bodyd);
xianshenglu
  • 4,943
  • 3
  • 17
  • 34