Dealing with a particular case where there are a number of elements with inline onclick
event triggers that also pass a variable that need to be preprocessed through an addEventListener
with the original onClick
removed, preferably through removeAttribute
as opposed to setAttribute("onclick", null)
.
<div onClick="alert('shoe');">shoe</div>
<div onClick="alert('epic');">epic</div>
<div onClick="alert('dogs');">dogs</div>
<div onClick="alert('army');">army</div>
For the sake of reuse and usefulness to others - the example above is simplified however there is no need to handle IE attachEvent
or detachEvent
and jQuery is not available (for me at least).
I've tried several approaches and my initial trial code looked like the following:
var fields = document.getElementsByTagName("div");
for (var i = 0; i < fields.length; i++) {
word = fields[i].getAttribute("onClick").substr(7,4);
fields[i].addEventListener("click", function() {console.log(word);}, false);
fields[i].removeAttribute("onclick");
}
Needles to say in most derivative approaches i've either managed to remove the onclick
but couldn't assign the event listener, could populate a words array but only with the last word and so forth.