为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 247 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号