Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading