I_love_vegetables
I_love_vegetables

Reputation: 1341

is there an alternative to for loop?

i have a function here that will put the innerHTML of each li element to an array

let li = document.getElementsByTagName("li");
let array = [];
for (var i = 0; i < li.length; i++) {
  array.push(li[i].innerHTML);
}

and im wondering if there is any alternative or faster way to do this

i tried using spread operator like this but it only shows the elements and idk how to get the innerHTML of each li

let array = [...li];

Upvotes: 0

Views: 59

Answers (2)

Lior Kaminsky
Lior Kaminsky

Reputation: 417

// Simple map function over the li elements
// Also use const on both variables ('li' and 'array') - as they are not being changed
const li = document.getElementsByTagName("li");
const array = [...li].map((e) => e.innerHTML);

Upvotes: 1

AndrewL64
AndrewL64

Reputation: 16311

You can use the map() method like this:

let lis = document.getElementsByTagName("li");
let array = [...lis].map(e => e.innerHTML);
console.log(array);
<ul>
  <li>SomeThing</li>
  <li>SomeThing</li>
  <li>SomeThing</li>
  <li>SomeThing</li>
</ul>

Upvotes: 3

Related Questions