let btn = [...document.querySelectorAll(".box__btn-resp")];
btn.forEach((e, i) => {if (e[i].onclick) {
e[i].style.borderBottom = "solid blue";});
I'm doing a quiz, and I'd like when the player clicks on one of the four options, it has a blue bottom border. I tried iterating through the elements with forEach, as you can see in the code above, but it didn't work that way. I could do this with addeventlistener, but it would be very repetitive. However, I'm not sure how to get it to work any other way. Does anyone know how to do this without getting repetitive? Thanks if you can help. I'm using Google Translate, so I'm sorry if there are any mistakes
CodePudding user response:
Why repetitive?
const btns = [...document.querySelectorAll(".box__btn-resp")];
btns.forEach(btn => btn.onclick = e => {
btns.forEach(_btn => _btn.style.borderBottom = "1px solid #333")
e.target.style.borderBottom = "solid blue"
})
<button >Click</button>
<button >Click</button>
<button >Click</button>
<button >Click</button>
<button >Click</button>
CodePudding user response:
Hello is this what you are looking for? This will take the button that is clicked and add a bottom border.
Single
var elem = document.getElementById("btn");
elem.addEventListener('click', function()
{
elem.style.borderBottom = "thick solid #0000FF";
});
<button id="btn">hello</button>
Multiple
var elements = document.getElementsByTagName('button');
for(var x=0; x<elements.length; x )
{
elements[x].addEventListener('click', function()
{
for(var z=0; z<elements.length; z )
{
elements[z].style.borderBottom = "thick solid #0000FF";
}
});
}
<button>Item 1</button>
<button>Item 2</button>
<button>Item 3</button>
<button>Item 4</button>