I am trying to run a pretty basic conditional to determine if a current element has a next sibling or not using ES6.
I have tried to determine if nextElementSibling returns as null
but this silently fails.
if (el.nextElementSibling == null) {
// do something if there is no next sibling
} else {
// do something if there is a next sibling
}
CodePudding user response:
Your code is working as expected, see my snippet below:
var el = document.querySelector('#brother')
if (el.nextElementSibling == null) {
console.log('there is no sibling')
} else {
console.log('there is a sibling')
}
<div>
<div id="brother"></div>
<!-- delete sister div below and the console will log 'there is no sibling' -->
<div id="sister"></div>
</div>
CodePudding user response:
Your method seems to work
document.querySelectorAll("div > p").forEach((el) => {
el.addEventListener("click", () => {
if (el.nextElementSibling == null) {
// do something if there is no next sibling
console.log("doesnt have next sibling");
} else {
// do something if there is a next sibling
console.log("has next sibling");
}
});
});
<div>
<p>paragraph 1 - click me</p>
<p>paragraph 2 - click me</p>
<p>paragraph 3 - click me</p>
</div>