Reputation: 7202
I'm trying to highlight any DOM element of a certain Web page when the user clicks on it. For that purpose, I iterate through all elements of the current element and disable any functionality (so e.g. I can click and not to be redirected):
var elems = window.document.getElementsByTagName('*');
for (var i = 0; i < elems.length; i++) {
elems[i].onclick = function(e){
e.preventDefault();
}
The thing is, when user clicks, a lot of click events are fired, because every element has tas behaviour, and I need to avoid unhighlight.
Any idea of how to improve that or any alternative? Thanks a lot!
P/d: It has to be pure JS
Upvotes: 0
Views: 6915
Reputation: 2135
I made a jsfiddle that does it:
https://jsfiddle.net/zgqpnaey/
var elems = window.document.getElementsByTagName('*');
for (var i = 0; i < elems.length; i++) {
myFunction(elems[i]);
}
function myFunction(element) {
element.onclick = function(e) {
e.preventDefault();
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
element.style.background = 'red';
};
}
somethinghere explained it above.
Also, you shouldn't bind onclick inside a loop, it's known to cause errors; it's better to call a function and pass the proper parameters.
Upvotes: 1
Reputation: 17358
You'll need to do two things: first of all, you want to actually add an event
, not redefine its click behaviour, and secondly, uou want it to not bubble
up through the dom. Try this:
var elems = window.document.getElementsByTagName('*');
for (var i = 0; i < elems.length; i++) {
// Use addEventListener to listen for events.
// Older version of IE use attachEvent, but I guess thats irrelevant.
elems[i].addEventListener("click", function(e){
e.preventDefault();
// Use stopImmediatePropagation to stop the element from passing this click to wrapping parents - because a click on a child is technically a click on the parent as well.
e.stopImmediatePropagation();
});
}
Heres more to read:
Add Event Listener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Stop Immediate Propagation: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation
As a brave editor says, you can also pass false
as a third argument to the addEventListener
and it does basically the same thing but is less comprehensible and does some additional things as well, so I have opted not to default to this just because its easier to understand that you are stopping propagation.
Upvotes: 1