skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. Instead of using previousSibling, use previousElementSibling instead.

    var div = document.getElementsByTagName("div")[0];
    var midp = div.children[1];
    var midPText = (midp.innerHTML = "This is the middle child");
    var firstp = div.children[1].previousElementSibling;
    var firstPText = (firstp.innerHTML = "This is the first child");
    <div>
      <p style="margin-top:2rem; background-color:#ccff33; padding:2rem; color:black;" id = "p1"></p>
      <p style="margin-top:2rem; background-color:#99cc00; padding:2rem; color:white;" id = "p2"></p>
      <p style="margin-top:2rem; background-color:#394d00; padding:2rem; color:white;" id = "p3"></p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search