How to hide any DOM element
I want to hide any element that is clicked. For example, if a button is pressed <p></p>
, it should be hidden, or if a button is pressed <div></div>
, it should be hidden. I tried using:
$(document).ready(function(){
$("*").click(function(){
$(this).hide();
});
});
However, this hides all elements if one element is clicked.
How can I achieve what I have described?
The event will trigger the DOM bubble until it reaches document
and then everything is hidden. You can stop this bubble using stopPropagation
in the event:
$("*").click(function(e) {
e.stopPropagation();
$(this).hide();
});
Also note that it is not recommended to add an event handler to every element in the DOM, as there can be thousands. Instead, bind a single handler document
using event delegation:
$(document).on('click', '*', function(e) {
e.stopPropagation();
$(this).hide();
});
Sample script
Alternatively, e.stopPropagation();
you can also hide just the target:
$("*").click(function(e) {
$(e.target).hide();
});