dwinnbrown dwinnbrown - 5 months ago 19
HTML Question

JS - Using 'this' and nextSibling - undefined is not an object

So in my html, I am running a function onclick of a button. I then want to obtain the

innerHTML;
value of the sibling of the element that was clicked on however I am getting the old 'undefined is not an object error'. This is my html structure:

<button onclick="helloWorld();">
Click Me
</button>
<p>
Hello
</p>


And my javascript:

<script>
function helloWorld() {
var justClicked = this;
var sibling = justClicked.nextSibling.textContent;
alert(sibling);
}
</script>


any ideas?

Answer

You can pass the this reference as parameter into your event handler:

function helloWorld(justClicked) {
  var sibling = justClicked.nextSibling.nextSibling.textContent;
  console.log(sibling);
}
<button onclick="helloWorld(this);">
  Click Me
</button>
<p>
  Hello
</p>

Also note that the line break between the <button> and the <p> is counted as a sibling, so you will have to skip it.

Comments