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回來了。
添加回答
舉報(bào)