Roshni
Roshni

Reputation: 199

How can I hide any DOM element

I want to hide any element that is clicked. For example, if <p></p> is clicked it should hide, or if <div></div> is clicked it should hide. I tried using:

$(document).ready(function(){
    $("*").click(function(){
        $(this).hide();
    });
});

However, this hides all the elements if one element is clicked.

How can I achieve what I described?

Upvotes: 3

Views: 55

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The event will bubble up the DOM until it reaches the document, and then everything is hidden. You can stop that bubbling by using stopPropagation on the event:

$("*").click(function(e) {
    e.stopPropagation();
    $(this).hide();
});

Also note that it's not a good idea to add an event handler to every element in the DOM as there could be thousands. Instead, bind a single handler to the document using event delegation:

$(document).on('click', '*', function(e) {
    e.stopPropagation();
    $(this).hide();
});

Example fiddle

Upvotes: 7

taxicala
taxicala

Reputation: 21759

As an alternate way of e.stopPropagation();, You could also hide only the targeted element:

$("*").click(function(e) {
    $(e.target).hide();
});

Upvotes: 3

Related Questions