⊗jsPmOEEE 418 of 504 menu

Event element in an Event object in JavaScript

The Event object also allows you to get the element where the event occurred. This element is contained in the property target. Why is this necessary if this element is contained in this?

The fact is that in fact this always contains the element to which the event was attached, and the target property - the element that was actually clicked. This real element may or may not match this.

Let's look at an example. Let's say we have a div with a paragraph inside it:

<div id="elem"> <p>text</p> </div>

Bind the event to the div, but click on the paragraph. Obviously, clicking on a paragraph is also a click on a div, since the paragraph is contained in our div.

In the described case, it turns out that the target property will contain the end tag in which the event happened - that is, a paragraph, not a div. Let's make sure of this:

let elem = document.querySelector('#elem'); elem.addEventListener('click', function(event) { console.log(event.target); // will output our paragraph console.log(this); // will output our div });

Let's say you have the list ul with li tags:

ul { padding: 30px; border: 1px solid red; } li { list-style-type: none; margin-bottom: 20px; border: 1px dashed black; } <ul id="elem"> <li>text</li> <li>text</li> <li>text</li> <li>text</li> <li>text</li> </ul>

:

Attach a click handler to the ul tag. In this handler, use the tagName property to check which tag was clicked. If the click was on the li tag, add an exclamation mark to the end of this tag text. And if the click was on the tag ul - show information about it in the console.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline