Cara menggunakan CLOESEST pada JavaScript

Cara menggunakan CLOESEST pada JavaScript
metode traversal jQuery

contoh

Kembali <span> elemen nenek moyang pertama adalah <ul> elemen:

$(document).ready(function(){
$("span").closest("ul").css({"color":"red","border":"2px solid red"});
});

hasil:

body (great-great-grandparent)

div (great-grandparent)

    ul (second ancestor - second grandparent)
      ul (first ancestor - first grandparent)
    • li (direct parent) span

Coba »


Definisi dan Penggunaan

() Metode yang paling dekat mengembalikan elemen yang dipilih dari elemen nenek moyang pertama.

ayah nenek moyang, kakek, buyut, dan seterusnya.

DOM tree: Metode ini melintasi naik dari elemen saat sampai semua jalan dari elemen akar dokumen (<html>), untuk menemukan elemen nenek moyang pertama DOM elemen.

Metode ini orang tua () mirip, keduanya melintasi up pohon DOM, perbedaannya adalah:

terdekat ()

  • Mulai dari elemen saat
  • Single pertama traversal leluhur bersama pohon DOM ke atas, dan mengembalikan ekspresi pencocokan berlalu
  • Kembali nol atau satu elemen dari jQuery objek

orang tua ()

  • Mulai dari elemen induk
  • Sepanjang DOM pohon traversal dan mengembalikan ekspresi cocok dengan semua nenek moyang berlalu
  • Kembali nol, satu atau lebih elemen dari objek jQuery

Metode lain yang terkait:

  • orang tua () - Mengembalikan elemen induk langsung dari elemen yang dipilih
  • parentsUntil () - Mengembalikan semua nenek moyang dari parameter elemen antara dua sampai

tatabahasa

Pengembalian elemen yang dipilih dari elemen nenek moyang pertama:

$(selector).closest( filter )

Pengembalian pohon DOM konteks DOM menemukan elemen nenek moyang pertama:

$(selector).closest( filter,context )


参数描述
filter 必需。规定缩小搜索祖先元素范围的选择器表达式、元素或 jQuery 对象。
context 可选。在其内可以找到匹配元素的 DOM 元素。

Cara menggunakan CLOESEST pada JavaScript

contoh yang lebih

Kembali <span> elemen nenek moyang pertama adalah <span> elemen
Karena metode ini dari awal elemen saat ini, pencarian <span> pertama <span>, akan kembali ke <span>.

Dalam elemen DOM sebagai konteks dilewatkan ke pencarian nenek moyang pertama
Dua parameter yang digunakan dalam elemen DOM dilewatkan sebagai konteks untuk mencari pertama <ul> elemen.


Cara menggunakan CLOESEST pada JavaScript
metode traversal jQuery

To get the closest element by a selector, you can use the element's closest() method. This method starts with the target Element and traverses up through its ancestors in the DOM tree until it finds the element that matches the selector.

Table of Contents

  • What is .closest in JavaScript?
  • How do you find the parent element of a class?
  • What is the difference between parentNode and parentElement?
  • What is the closest method?

The closest() method returns the first element that matches the selector. If no such element exists, it returns null.

Let us say you have the following HTML code snippet:

<article>
    <h2 class="title">How to learn JavaScript</h2>
    <div class="meta">
        <p class="subtitle">12 tips to learn JavaScript quickly and free.</p>
        <time class="published">August 21, 2019</time>
    </div>
</article>

The following example selects the closest <div> element of the selected element:

const elem = document.querySelector('time');

// select closest <div>
const div = elem.closest('div');

console.log(div.classList[0]); // meta

Here is an another example that selects the closest <article> element in the DOM tree:

const elem = document.querySelector('time');

const article = elem.closest('article');

console.log(article.tagName); // article

The closest() method doesn't work for siblings. For example, you can not select the <p> tag because it is a sibling of <time> and not its parent. The same logic applies to <h2> tag because it is not a parent node of <time> in the DOM tree:

elem.closest('p'); // null
elem.closest('h2'); // null

To select a sibling of an element, you have to first select the closest parent element and then use querySelector() to find the sibling within:

elem.closest('div').querySelector('p').innerText; 
// 12 tips to learn JavaScript quickly and free.

elem.closest('article').querySelector('h2').innerText; 
// How to learn JavaScript

The closest() method only works in modern browsers and doesn't support Internet Explorer. To support IE9 and above, you can use the following polyfill:

// https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill

if (!Element.prototype.matches) {
  Element.prototype.matches =
    Element.prototype.msMatchesSelector || 
    Element.prototype.webkitMatchesSelector;
}

if (!Element.prototype.closest) {
  Element.prototype.closest = function(s) {
    var el = this;

    do {
      if (Element.prototype.matches.call(el, s)) return el;
      el = el.parentElement || el.parentNode;
    } while (el !== null && el.nodeType === 1);
    return null;
  };
}

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

What is .closest in JavaScript?

The closest() method in JavaScript is used to retrieve the closest ancestor, or parent of the element matches the selectors. If there is no ancestor found, the method returns null.

How do you find the parent element of a class?

Use the closest() method to get the closest parent element by class, e.g. child. closest('. parent') . The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.

What is the difference between parentNode and parentElement?

parentNode gives the parent, while . parentElement gives undefined.

What is the closest method?

closeTo(double operand, double error) Creates a matcher of Double s that matches when an examined double is equal to the specified operand , within a range of +/- error .