Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I call and update the child element using its sibling?

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue is because in between the <div> elements is a TextNode. This is being selected by previousSibling instead of the div 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.

var div = document.getElementsByTagName("div")[0];
var midp = div.children[1];
var midPText = (midp.innerHTML = "This is the middle child");
var firstp = midp.previousElementSibling;
var firstPText = firstp.innerHTML = "This is the first child";
div>p {
  margin-top: 2rem;
  padding: 2rem;
  color: white;
}

div>p:nth-child(1) {
  background-color: #ccff33;
  color: black;
}

div>p:nth-child(2) {
  background-color: #99cc00;
}

div>p:nth-child(3) {
  background-color: #394d00;
}
<div>
  <p></p>
  <p></p>
  <p></p>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading