--- title: Element.closest() slug: Web/API/Element/closest tags: - دوم - مرجع - واجهة برمجة تطبيقات translation_of: Web/API/Element/closest ---
{{APIRef('DOM')}}
ال closest() method تجتاز {{domxref ("Element")}} والأصل(يتجهون نحو جذر المستند) حتى يعثروا على عقدة تتطابق مع الstring المحدد. سيعود نفسه أو أسلاف مطابقة. إذا لم يكن هناك مثل هذا العنصر ، فإنه يعيد null.

تركيب الجملة

var closestElement = targetElement.closest(selectors);

المعاملات

القيمة المرجعة

استثناءات

مثال

HTML

<article>
  <div id="div-01">Here is div-01
    <div id="div-02">Here is div-02
      <div id="div-03">Here is div-03</div>
    </div>
  </div>
</article>

JavaScript

var el = document.getElementById('div-03');

var r1 = el.closest("#div-02");
// returns the element with the id=div-02

var r2 = el.closest("div div");
// returns the closest ancestor which is a div in div, here it is the div-03 itself

var r3 = el.closest("article > div");
// returns the closest ancestor which is a div and has a parent article, here it is the div-01

var r4 = el.closest(":not(div)");
// returns the closest ancestor which is not a div, here it is the outmost article

Polyfill

بالنسبة للمتصفحات التي لا تدعم ()Element.closest ، ولكنها تدعم ال()element.matches (أو ما يعادله سابقًا ، بمعنى IE9 +) ، توجد تعبئة متعددة:

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;
  };
}

ومع ذلك ، إذا كنت تحتاج بالفعل إلى دعم IE 8 ، فإن polyfill التالي سيقوم بالمهمة ببطء شديد ، ولكن في النهاية. ومع ذلك ، ستدعم فقط محددات CSS 2.1 في IE 8 ، ويمكن أن تسبب تأخر كبير في إنتاج المواقع .

if (window.Element && !Element.prototype.closest) {
  Element.prototype.closest =
  function(s) {
    var matches = (this.document || this.ownerDocument).querySelectorAll(s),
        i,
        el = this;
    do {
      i = matches.length;
      while (--i >= 0 && matches.item(i) !== el) {};
    } while ((i < 0) && (el = el.parentElement));
    return el;
  };
}

مواصفات

مواصفات الحالة تعليق
{{SpecName('DOM WHATWG', '#dom-element-closest', 'Element.closest()')}} {{Spec2('DOM WHATWG')}} تعريف ابتدائي.

التوافق مع المتصفحات

{{Compat("api.Element.closest")}}

ملاحظات التوافق

إقرأ أيضا