How can I get getElementsByClassName
to work? Want to replace getElementById
which is working just fine, but need to fetch classes instead.
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();
2
Answers
getElementById
returns a single HTML element, butgetElementsByClassName
returns anHTMLCollection
(comparable to an array, hence the plural form of elements) of HTML elements. You should access the first element in the return value ofgetElementsByClassName
(note[0]
at the end):It’s a common mistake, but
getElementsByClassName
returns aHTMLCollection
(just think of an array here).If you want to get the first element with className of
something2
you can doThe 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