I am trying to change all border colors on the current page once a button is clicked. I do this by toggling a class and define that class in CSS.
var all = document.querySelector("*") changeBorder = function() { all.classList.toggle("border"); }
*.border { border-style: solid; border-color: green; } div { border: 1px solid black; }
<button onclick="changeBorder()">Change the borders</button> <div>Border</div> <div>Border</div> <div>Border</div> <div>Border</div> <div>Border</div>
The code above does not work as it applies a border to everything on the page, and removing the “border-style” will make the code invalid.
Advertisement
Answer
First try to avoid on
HTML attributes to invoke functions, instead use a selector with addEventListener
Here is a basic code to do what you’re trying to achieve by using classList
inside a loop forEach
//short version document.querySelector('.js-toggle').addEventListener('click', () => document.querySelectorAll('div').forEach(el => el.classList.toggle('red'))) //regular version //document.querySelector('.js-toggle').addEventListener('click', () => { // document.querySelectorAll('div').forEach((el) => { // el.classList.toggle('red') // }) //})
div { border: 1px solid black } .red { border-color: red }
<button class='js-toggle'>Change the borders</button> <div>Border</div> <div>Border</div> <div>Border</div> <div>Border</div> <div>Border</div>
If you really want to select all the elements to change border, you can use the wildcard selector *
//short version document.querySelector('.js-toggle').addEventListener('click', () => document.querySelectorAll('*').forEach(el => el.classList.toggle('red'))) //regular version //document.querySelector('.js-toggle').addEventListener('click', () => { // document.querySelectorAll('*').forEach((el) => { // el.classList.toggle('red') // }) //})
div { border: 1px solid black } .red { border-color: red }
<button class='js-toggle'>Change the borders</button> <div>Border</div> <div>Border</div> <div>Border</div> <div>Border</div> <div>Border</div>