JavaScript >> Javascript 文檔 >  >> JavaScript

使用 JavaScript 通過選擇器獲取最近的元素

要通過選擇器獲取最近的元素,可以使用元素的 closest() 方法。此方法以目標 Element 開頭 並在 DOM 樹中向上遍歷其祖先,直到找到與選擇器匹配的元素。

closest() 方法返回匹配選擇器的第一個元素。如果不存在這樣的元素,則返回 null .

假設您有以下 HTML 代碼片段:

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

以下示例選擇最近的 <div> 被選元素的元素:

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

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

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

這是另一個選擇最近的 <article> 的示例 DOM 樹中的元素:

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

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

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

closest() 方法不適用於兄弟姐妹。例如,您不能選擇 <p> 標記,因為它是 <time> 的兄弟 而不是它的父母。同樣的邏輯適用於 <h2> 標記,因為它不是 <time> 的父節點 在 DOM 樹中:

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

要選擇元素的同級元素,您必須首先選擇最近的父元素,然後使用 querySelector() 在裡面找到兄弟姐妹:

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

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

closest() 方法僅適用於現代瀏覽器,不支持 Internet Explorer。要支持 IE9 及以上版本,可以使用以下 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;
  };
}

Tutorial JavaScript 教程
  1. ✏ 在 webpack 中處理 CSS |提取 CSS

  2. 是否可以使用 jQuery 為 scrollTop 設置動畫?

  3. React 教程通常會跳過的概念

  4. 使用 Firefox 90 變得生動起來

  5. 概括

  6. 由 InversifyJS 提供支持的 TypeScript 應用程序中的依賴注入

  7. 我們真的需要 deno 的包管理器嗎?

  1. 我創建了 Hoppscotch 👽 - 開源 API 開發生態系統

  2. JavaScript 中 Fetch API 中唯一能讓你在職業生涯中走得更遠的部分

  3. 2022 年使用的 6 個最佳 JavaScript 框架

  4. 錯誤:期望驗證器返回 Promise 或 Observable

  5. 為什麼我更喜歡對象而不是 switch 語句

  6. 更好的後端 DX:Fastify + ESBuild =⚡️

  7. 我建立了我的個人網站

  1. Redux 困惑:Redux 到底是什麼?什麼是狀態?為什麼我們需要狀態管理器?

  2. 設置函數參數的類型?

  3. 我如何使用 NodeJS(+ 可用代碼)在 dev.to 上找到最佳發佈時間

  4. 使用 NestJS、Fastify 和 TypeORM 創建 REST 應用程序