我要检查,如果nextElementSibling元素存在,且如果它是一个场。但我没有找到正确的JS请求。
document.getElementById($id).nextElementSibling.type
不工作。
您需要使用节点名称或标记名。
var nextElement = document.getElementById('demo').nextElementSibling.nodeName;
console.log(nextElement);
<div id="demo">
<p>
hola
</p>
</div>
<p>
next element
</p>
您可以使用quertSelector
和+*
得到一个同级
let nextSibling = document.querySelector('#main+*')
if(!nextSibling){
console.log("There is no next sibling")
}
else if(nextSibling.nodeName === "INPUT"){
console.log("Next sibling is input field")
}
else {
console.log("next sibling exists but its not input field")
}
console.log(nextSibling);
<div><div id="main">This is my element</div>
<input type="text" placeholder="I am first sibling" />
<input type="text" placeholder="I am second sibling" />
</div>
<span></span>