I’m currently learning JavaScript and testing out how to call and update the children of an element. I was able to update the middle child and I would now like to update the first child using the middle child, I’m not sure what I’m doing wrong.
var div = document.getElementsByTagName("div")[0];
var midp = div.children[1];
var midPText = (midp.innerHTML = "This is the middle child");
var firstp = midp.previousSibling;
var firstPText = firstp.innerHTML = "This is the first child";
<div>
<p style="margin-top:2rem; background-color:#ccff33; padding:2rem; color:black;"></p>
<p style="margin-top:2rem; background-color:#99cc00; padding:2rem; color:white;"></p>
<p style="margin-top:2rem; background-color:#394d00; padding:2rem; color:white;"></p>
</div>
2
Answers
The issue is because in between the
<div>
elements is a TextNode. This is being selected bypreviousSibling
instead of thediv
you’re trying to target.To do what you require use
previousElementSibling
instead. This will select Elements only, not nodes.Also, as a side note, don’t use inline styling. Put your CSS in an external stylesheet.
Instead of using
previousSibling
, usepreviousElementSibling
instead.