亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript - 通過內部文本獲取元素 id

Javascript - 通過內部文本獲取元素 id

慕無忌1623718 2022-05-26 11:08:55
我正在尋找一種通過部分內部 html 獲取元素 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>我猜不出<div>id(沒有后綴,沒有前綴,沒有其他屬性......)我必須獲取元素的唯一方法是通過內部跨度中的文本(我之前可以找到的文本)我嘗試過類似的東西identifiers = document.querySelectorAll("[textContent*='persistant text']").id;但總是返回“未定義”有人有線索嗎?
查看完整描述

1 回答

?
森林海

TA貢獻2011條經驗 獲得超2個贊

如果您可以獲得對后代元素的引用,那么您可以使用以下.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 的兩個元素是無效的 HTML,并且首先破壞了具有 ID 的目的。


此外,[textContent*='persistant text']沒有工作,因為當您將某些內容傳遞[]到 intoquerySelector()或者querySelectorAll()您表示您正在搜索 HTML 元素的屬性時。textContent不是 HTML 元素的屬性,它是 DOM 元素節點的屬性。因此,沒有任何內容與您的搜索匹配,因此,您undefined回來了。


查看完整回答
反對 回復 2022-05-26
  • 1 回答
  • 0 關注
  • 232 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號