简体   繁体   中英

How to access nested child node using javascript

This the code, I need to access the second <p> element using javascript, I have tried many things unable to access it. Please help me on this

<div class="demo">
  <div>
    <p>Some Text...</p>
    <p><b>Author:</b> Author Name</p>
    <p>Some Text...</p>
  </div>
</div>

You can use getElementsByTagName() and get the second element in the list.

const secondP = document.getElementsByTagName("p")[1];

you can get element by their tag name check this documentation: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName

const allParas = document.getElementsByTagName('p'); // collection of all p tags
allParas[1]; // sencond p tag

You can select the second p tag using nth-child . I have colored the text red, for demonstration purposes.

 let p = document.querySelector(".demo div p:nth-child(2)") p.style.color = "red";
 <div class="demo"> <div> <p>Some Text... </p> <p><b>Author:</b> Author Name </p> <p>Some Text... </p> </div> </div>

As shown in the accepted answer you can safely use the nth-child(n) selector however that's perhaps more suitable for dynamically accessing the n 'th child. Such as;

var n = 2;
document.querySelector(`.demo div p:nth-child(${n})`);

On the other hand CSS selector combinators are also very powerful. If you simply want to access the very next <p> coming after the first <p> which is directly under a <div> which is directly under an element with .demo class. So ".demo > div > p + p" should be sufficient. In this particular case we don't have any nested div s under .demo so we can also do like ".demo div p + p" .

 var el = document.querySelector(".demo > div > p + p"); console.log(el.textContent)
 <div class="demo"> <div> <p>Some Text...</p> <p><b>Author:</b> Author Name</p> <p>Some Text...</p> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM