第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Javascript - 通過內(nèi)部文本獲取元素 id

Javascript - 通過內(nèi)部文本獲取元素 id

慕無忌1623718 2022-05-26 11:08:55
我正在尋找一種通過部分內(nèi)部 html 獲取元素 id 的方法例如,我有這個(gè)模板<div id="unpredictable-id1">    <label>        <span id="unpredictable-id1"> (unpredictable text) </span> <!-- this span have has the same id than div but has unpredictable content -->        <span>persistant text</span> <!-- this span have no id, no class, no identifier -->    </label></div>我猜不出<div>id(沒有后綴,沒有前綴,沒有其他屬性......)我必須獲取元素的唯一方法是通過內(nèi)部跨度中的文本(我之前可以找到的文本)我嘗試過類似的東西identifiers = document.querySelectorAll("[textContent*='persistant text']").id;但總是返回“未定義”有人有線索嗎?
查看完整描述

1 回答

?
森林海

TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊

如果您可以獲得對后代元素的引用,那么您可以使用以下.closest()方法:


// Get all the span elements and loop through them

document.querySelectorAll("span").forEach(function(element){

  // Check the textContent of the element for a match

  if(element.textContent === "persistant text"){

    // Find the nearest ancestor div

    let closest = element.closest("div")

    // ...then do whatever you want with it

    console.log("The " + closest.nodeName + " has an id of: " + closest.id);

  }

});

<div id="unpredictable-id1">

    <label>

        <span id="unpredictable-id1"> (unpredictable text) </span> <!-- this span have has the same id than div but has unpredictable content -->

        <span>persistant text</span> <!-- this span have no id, no class, no identifier -->

    </label>

</div>


僅供參考:ID 在文檔中必須是唯一的。具有相同 ID 的兩個(gè)元素是無效的 HTML,并且首先破壞了具有 ID 的目的。


此外,[textContent*='persistant text']沒有工作,因?yàn)楫?dāng)您將某些內(nèi)容傳遞[]到 intoquerySelector()或者querySelectorAll()您表示您正在搜索 HTML 元素的屬性時(shí)。textContent不是 HTML 元素的屬性,它是 DOM 元素節(jié)點(diǎn)的屬性。因此,沒有任何內(nèi)容與您的搜索匹配,因此,您undefined回來了。


查看完整回答
反對 回復(fù) 2022-05-26
  • 1 回答
  • 0 關(guān)注
  • 226 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號