You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constdata=document.querySelector('div');console.log(data.innerText);console.log(data.textContent);// will only print Hello because it only shows visible text
constdata=document.querySelector('#test').dataset;// list all data attributesconsole.log(data);// get specific data attributeconsole.log(data.blue);console.log(data.yellowBlack);// define new data attributedata.green='green';
Capturing phase – the event goes down to the element.
Target phase – the event reached the target element.
Bubbling phase – the event bubbles up from the element.
<style>body* {
margin:10px;
border:1px solid blue;
}
</style><form>FORM
<div>DIV
<p>P</p></div></form><script>for(letelemofdocument.querySelectorAll('*')){elem.addEventListener("click",e=>alert(`Capturing: ${elem.tagName}`),true);elem.addEventListener("click",e=>alert(`Bubbling: ${elem.tagName}`));}</script><!--The code sets click handlers on every element in the document to see which ones are working.If you click on <p>, then the sequence is:HTML → BODY → FORM → DIV (capturing phase, the first listener):P (target phase, triggers two times, as we've set two listeners: capturing and bubbling)DIV → FORM → BODY → HTML (bubbling phase, the second listener).There's a property event.eventPhase that tells us the number of the phase on which the event was caught. But it's rarely used, because we usually know it in the handler.-->
Event Bubbling
The process is called "bubbling", because events "bubble" from the inner element up through parents like a bubble in the water. Normally it goes upwards till , and then to document object, and some events even reach window, calling all handlers on the path.
form.onclick=function(event){alert("target = "+event.target.tagName+", this="+this.tagName);};/*If p is clicked then: event.target = p | this = formIf div is clicked then: event.target = div | this = formIf form is clicked then: event.target = form | this = form*/
Stop bubbling (.stopPropagation())
event.stopPropagation() stops the move upwards, but on the current element all other handlers will run.
// body.onclick doesn't work if you click on <button><bodyonclick="alert(`the bubbling doesn't reach here`)"><buttononclick="event.stopPropagation()">Click me</button></body>
Stop all other handler execution on the same element (.stopImmediatePropagation())
To stop the bubbling and prevent handlers on the current element from running, there's a method event.stopImmediatePropagation(). After it no other handlers execute.