I have div question and one for each answer:
<div id="question"></div>
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>
<div id="e"></div>
when user click in one div I'd to 'select' it adding a css background.
So, I did:
var divA = document.getElementById('a');
divA.addEventListener('click', function () {
remove();
divA.classList.add("select");
},false);
var divB = document.getElementById('b');
divB.addEventListener('click', function () {
remove();
divB.classList.add("select");
},false);
... same thing to C, D and E.
I'd like to not repeat the code for each div select. any ideas how to avoid all this divA, divB, divC, divD, divE functions and add all in one?
my remove function:
function remove(){
document.getElementById('a').classList.remove("select");
document.getElementById('b').classList.remove("select");
document.getElementById('c').classList.remove("select");
document.getElementById('d').classList.remove("select");
document.getElementById('e').classList.remove("select");
}
document.querySelectorAll, select all the elements by a class. Loop over them and add an event handler to them. The event handler can reference the element clicked with theevent.targetorthiswithin the callback.sharedclassis much cleaner than#id1, #id2, #id3, #id4, ...