微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

最近元素 id JS

如何解决最近元素 id JS

有人可以帮助我如何获取最接近按钮的元素的 id 吗?

 function Myfunc(ev) {
 document.getElementbyId("demo").innerHTML = $(#ME).closest("div").attr('id');
 }
<div id="target1">1 div</div>
<button onclick="Myfunc(this)" id="ME">Click me to see id of those 2 elements</button>
<div id="target2">2 div</div>

<p id="demo"></p>

解决方法

.closest 的作用是导航到与选择器匹配的 ancestor 元素。由于您想要的元素不是所点击元素的祖先,.closest 不是正确的工具。

我会使用 previousElementSiblingnextElementSibling

function Myfunc(elm) {
 document.getElementById("demo").innerHTML = elm.previousElementSibling.id + ' and ' + elm.nextElementSibling.id
 }
<div id="target1">1 div</div>
<button onclick="Myfunc(this)" id="ME">Click me to see id of those 2 elements</button>
<div id="target2">2 div</div>

<p id="demo"></p>

请注意,您需要使用 getElementById,而不是 getElementbyId。此外,如果可能的话,请使用 JS 而不是使用内联处理程序正确附加侦听器(这被普遍认为是不好的做法):

document.querySelector('#ME').addEventListener('click',function() {
 document.getElementById("demo").textContent = this.previousElementSibling.id + ' and ' + this.nextElementSibling.id;
});
<div id="target1">1 div</div>
<button id="ME">Click me to see id of those 2 elements</button>
<div id="target2">2 div</div>

<p id="demo"></p>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。