Take two "arrays" in one line?

Asked

Viewed 40 times

2

It has for example, how to take the two in one line?

Example:

document.getElementsByClassName("teste")[0].removeAttribute("disabled");

I want to get the 0 and the 1

There’s a way to get the two together, or I’ll have to create two lines like this;

document.getElementsByClassName("teste")[0].removeAttribute("disabled");

document.getElementsByClassName("teste")[1].removeAttribute("disabled");

?

  • 2

    Either that or a loop

  • the position of the array [0] e [1] will always be fixed?

2 answers

3

With ES6 you can do it in one line like this:

[...document.getElementsByClassName("teste")].forEach(el => el.removeAttribute("disabled"));

But with "old" Javascript it has to be with a loop:

var els = document.getElementsByClassName("teste");
for (var i = 0; i < els.length; i++){
    els[i].removeAttribute("disabled")
}
  • In ES6 is a line but is also a loop :)

  • @bfavaretto yes, exact :)

  • "el" would be what? Thank you for the reply!

  • @Lucascarvalho forEachpasses a variable to the callback that runs for each element. The el was the name I gave to this variable and that is one of the elements with the class teste, one at a time.

  • Very good, but it’s only to enable the first two controls, so you would have to use one Array.filter() or something like that

  • @Wtrmute in this case see no need to use the .filteras there is no need to return an array with fewer elements filtered by a condition.

  • @Sergio: Maybe, but here you are disabling all the controls with the class teste, instead of just the first two, as the question asks.

  • @Wtrmute was not clear to me that it would only be the first two elements but in this case you can use . Slice(0, 1) to reduce the array.

Show 3 more comments

0

That should work:

Array.from(document.getElementsByClassName("teste")).map((ele, idx)=> idx === 0 || idx ===1 ?  ele.removeAttribute("disabled") : ele);

EDIT:

The method getElementsByClassName does not return a array. So you have to convert it into array for this solution to work. I edited the answer by converting to array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.