猿问

Javascript - 通过内部文本获取元素 id

我正在寻找一种通过部分内部 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;但总是返回“未定义”


有人有线索吗?


慕无忌1623718
浏览 248回答 1
1回答

森林海

如果您可以获得对后代元素的引用,那么您可以使用以下.closest()方法:// Get all the span elements and loop through themdocument.querySelectorAll("span").forEach(function(element){&nbsp; // Check the textContent of the element for a match&nbsp; if(element.textContent === "persistant text"){&nbsp; &nbsp; // Find the nearest ancestor div&nbsp; &nbsp; let closest = element.closest("div")&nbsp; &nbsp; // ...then do whatever you want with it&nbsp; &nbsp; console.log("The " + closest.nodeName + " has an id of: " + closest.id);&nbsp; }});<div id="unpredictable-id1">&nbsp; &nbsp; <label>&nbsp; &nbsp; &nbsp; &nbsp; <span id="unpredictable-id1"> (unpredictable text) </span> <!-- this span have has the same id than div but has unpredictable content -->&nbsp; &nbsp; &nbsp; &nbsp; <span>persistant text</span> <!-- this span have no id, no class, no identifier -->&nbsp; &nbsp; </label></div>仅供参考:ID 在文档中必须是唯一的。具有相同 ID 的两个元素是无效的 HTML,并且首先破坏了具有 ID 的目的。此外,[textContent*='persistant text']没有工作,因为当您将某些内容传递[]到 intoquerySelector()或者querySelectorAll()您表示您正在搜索 HTML 元素的属性时。textContent不是 HTML 元素的属性,它是 DOM 元素节点的属性。因此,没有任何内容与您的搜索匹配,因此,您undefined回来了。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答