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回来了。
添加回答
举报