-
Uncaught TypeError: Cannot set properties of undefined (setting 'background')
Code -
function changeBg() { document.getElementsByClassName("about-opt").style.background = "#99f";
}
getElementsByClassName returns a collection of elements, not a single element
Yeah, I'm changing bg of multiple items
Use changeBg() function
Do a google search for- changeBg function javascript
Simple: Use loop.Why don't you use adding a class instead of directly applying the style?
function changeBackGround(){ //if is one element let element = document.querySelector(".about-opt"); if(element){ element.style.background = "#99f"; } //if is more thnan one element let elements = document.querySelectorAll(".about-opt"); for(let el of elements)[ el.style.background = "#99f"; ] }
Don't spoon feed by sharing the whole code
they won't learn anything
yes you right.
I want to change the background colour of elements using onclick of a button: Here is a sample - <button onclick="changeBg()"> This is js code - function changeBg() { document.getElementsByClassName("about-opt").style.background = "#99f"; }
The proper way is to toggle a class on your body element, you css styles then match the body class and element
toggle a class by javascript?
Actually that's the most efficient way i can think of, without looping through every element
Обсуждают сегодня