Search code examples
javascripthtmlcsscss-selectorsqueryselector

nth-child css selector not working correctly if we had <br> tag in sibling of children elements


a simple <div> with 5 <span> as children that end of any <span> i have <br> tag too.
when i want to select by :nth-child(x) any span element with index of more than 1 it's not worked
even selecting by document.querySelector() not worked
i test it on FireFox and Chrome too
when i removed <br> tags it's worked

how it's possible ?

console.log("i have 5 span children as well : ", document.querySelectorAll(".div1>span").length);

console.log("second span child is null : ", document.querySelector(".div1>span:nth-child(2)"));

console.log("third span child is second span element : ", document.querySelector(".div1>span:nth-child(3)").textContent);

console.log("select second element by another way: ", document.querySelectorAll(".div1>span")[1].textContent);

console.log("tag name of second child: ", document.querySelector(".div1>*:nth-child(2)").tagName);
html>body>div.div1>span:nth-child(2) {
  color: blue;
}
<html>

<body>
  <div class="div1">
    <span>this is example text 1</span>
    <br>
    <span>this is example text 2</span>
    <br>
    <span>this is example text 3</span>
    <br>
    <span>this is example text 4</span>
    <br>
    <span>this is example text 5</span>
    <br>
  </div>
</body>

</html>


Solution

  • The queries work as expected. When you run .div1>span:nth-child(2) you are requesting for a span element that is the second child of its parent, in this case div1. Second child of div1 is a <br> and therefore you get null.

    As suggested by Hao Wu, you should use :nth-of-type

    document.querySelector(".div1>span:nth-of-type(2)") This will search for the second span element that is a child of div1

    console.log("i have 5 span children as well : ", document.querySelectorAll(".div1>span").length);
    
    console.log("second span child is null : ", document.querySelector(".div1>span:nth-of-type(2)"));
    
    console.log("third span child is second span element : ", document.querySelector(".div1>span:nth-of-type(3)").textContent);
    
    console.log("select second element by another way: ", document.querySelectorAll(".div1>span")[1].textContent);
    
    console.log("tag name of second child: ", document.querySelector(".div1>*:nth-child(2)").tagName);
    html>body>div.div1>span:nth-of-type(2) {
      color: blue;
    }
    <html>
    
    <body>
      <div class="div1">
        <span>this is example text 1</span>
        <br>
        <span>this is example text 2</span>
        <br>
        <span>this is example text 3</span>
        <br>
        <span>this is example text 4</span>
        <br>
        <span>this is example text 5</span>
        <br>
      </div>
    </body>
    
    </html>