Probably an easy javascript question regarding classes

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();                

>Solution :

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];

Leave a Reply