0

How can I get getElementsByClassName to work? Want to replace getElementById which is working just fine, but need to fetch classes instead.

Codepen here

HTML:

<div class="spinner-displayer3"></div>    
<div id="something"  class="something2">Click orange box!</div>

CSS:

#something, .something2 {
  margin:150px 0 0 150px;
  background-color:orange;
  width:130px;
}
   
.loading2 {
position:fixed;                      
top:0;
left:0;
z-index:1000001;
width:100%; 
height:100%;
background-image: url("https://tradinglatam.com/wp-content/uploads/2019/04/loading-gif-png-4.gif");
border: 2px solid #ccc;
width: 100%;
height:100%;
background-color: white;
background-color: rgba(255, 255, 255, 0.8); 
background-repeat: no-repeat;
background-position: center;
}

Now to the JS...

...Working JSS (fetching ID):

function spinner() {
   const spinnerDisplayer = document.querySelector(".spinner-displayer3");
   const btn = document.getElementById("something");

   btn.addEventListener('click', () => {
   spinnerDisplayer.classList.add("loading2");

 })
}     
spinner();                

...Not working JS (fetching class):

function spinner() {
   const spinnerDisplayer = document.querySelector(".spinner-displayer3");
   const btn = document.getElementsByClassName("something2");

   btn.addEventListener('click', () => {
   spinnerDisplayer.classList.add("loading2");
 
 })
}     
spinner();                
Mr_G
  • 127
  • 1
  • 12

2 Answers2

1

getElementById returns a single HTML element, but getElementsByClassName returns an HTMLCollection (comparable to an array, hence the plural form of elements) of HTML elements. You should access the first element in the return value of getElementsByClassName (note [0] at the end):

const btn = document.getElementsByClassName("something2")[0];
  • 1
    Thanks! I really appreciate your answer. Even though the question was easy, it does not take away the fact that you saved me a lot of time! – Mr_G Jun 17 '23 at 12:41
1

It's a common mistake, but getElementsByClassName returns a HTMLCollection (just think of an array here). If you want to get the first element with className of something2 you can do

btn = document.getElementsByClassName("something2")[0];
btn.on...

The main use of getting by className instead of id is that you can have multiple elements with the same className. You can do something for each element with a certain classname like this

Object.values(document.getElementsByClassName("something2")).forEach(btn => {
    btn.on...
});
SollyBunny
  • 800
  • 1
  • 8
  • 15