HOW TO RETRIEVE MULTIPLE ID/CLASS in JS

I wonder why I cant style multiple elements with the same Id using JS with this code :

var x = document.getElementById('foo').style["opacity"] = "0";

Maybe this is the reason why its a bad practice to set single ID to multiple elements… Thats why I used class with this code:

var x = document.getElementByClassName('foo').style["opacity"] = "0";

But I see no results, and when i looked at the console it says!

document.getElementByClassName(); is not a function!

So, how am i able to retrieve a class to use it in my JAVASCRIPT?

1 Like

document.getElementsByClassName() => Elements instead of Element

EDIT: But I don’t think you can directly use .style on it.

2 Likes

var x = document.querySelectorAll(’.foo’).style[“opacity”] = “0”;

where .foo is a class name /…
it should work fine…

var x = document.getElementsByClassName(‘foo’)[0].style[“opacity”] = “0”;
This will fetch the first element tag having the name “foo” .

Im sorry @RAY_V101 but your solution cant seem to fix my problem
and sir @BenGitter’s as well

getElementsByClassName() returns an array-like structure. You will have to loop over it to set the styles.

Code using a for…of loop:

var x = document.getElementsByClassName('foo');
for(var el of x){
  el.style["opacity"] = "0";
}

worked like a charm! Cool!

Im actually making my own dropdown list/nav theme without any library… ie using VANILLA :joy:

what u talking about :slight_smile: brooo
this works fine:
var x = document.querySelectorAll(“.foo”);
x[0].style[“opacity”] = 0;

Also try not to use one id for multiple elements, since is an id it supposed to be unique for that element, is not a good practice to have an id for several elements, use class instead. ID is useful if you want to target one specific element and do some stuff to it.

yes but will that x[0] selects the element with the class foo that is first in the array of var x?

var x = document.querySelectorAll(".foo");
x[0].style[“opacity”] = 0;

okay then do this , i was jus explaining you with raw info

var x = document.querySelectorAll(".foo");
for( i of x) {
i.style.opacity = 0 ;
}