最近元素 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>