Следите за новинками
в нашем Telegram канале. Жми, чтобы подписаться:)
150 of 264 menu
◀ ▶

closest method

The closest method searches for the closest parent element that matches the specified CSS selector, while the element itself is also included in the search.

Syntax

element.closest('selector');

Example

Let's find among the parents of an element the element with the class www:

<div class="www" id="parent2"> <div class="ggg" id="parent1"> <p class="zzz" id="child"></p> </div> </div> let elem = document.querySelector('#child'); let parent = elem.closest('.www'); console.log(parent.id);

The code execution result:

'parent2'

Example

Let's find among the parents of an element the element with the class www. As a result, we will get a reference to the element itself, since it has this class itself:

<div class="www" id="parent2"> <div class="www" id="parent1"> <p class="www" id="child"></p> </div> </div> let elem = document.querySelector('#child'); let parent = elem.closest('.www'); console.log(parent.id);

The code execution result:

'child'

See also

  • the matches method
    that checks an element by a selector
  • the contains method
    that checks a child by a selector
← →
↑
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