'Why do all elements disappear with "*" selector?
I'm learning JQuery through w3school. And I came across this example.
From my understanding, $("*").dblclick() bind the double click event to each element in the document (each element has its own event and they are seperated).
And, I expect that, after double clicking a <p> element, only the one clicked will disappear. However, when I click a <p> element, every <p> element disappears. May I know how is my understanding wrong?
Solution 1:[1]
"*" selects ALL elements, including <body> and <html> (https://api.jquery.com/all-selector/). So, if you double click one of your paragraphs, the event will be triggered three times, one for <p>, one for <body> and one for <html> generating this "undesired" behavior. If one of your <p> was inside, lets say, a <div>, the event would be triggered four times. One way to prevent this is to stop the event propagation.
$( function() {
$( "*" ).dblclick( function( event ){
console.log( event.target.innerHTML );
console.log( event.target.parentElement.tagName );
$(this).hide();
event.stopPropagation();
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>aaaaaa</p>
<p>bbbbbb</p>
<p>cccccc</p>
<div>
<p>dddddd</p>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | davidbuzatto |
