[英]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.这是代码,我需要使用 javascript 访问第二个
<p>
元素,我尝试了很多无法访问它的方法。 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.您可以使用
getElementsByTagName()
并获取列表中的第二个元素。
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您可以通过标签名称获取元素检查此文档: 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
.您可以使用
nth-child
select 第二个p
标签。 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.如接受的答案所示,您可以安全地使用
nth-child(n)
选择器,但这可能更适合动态访问第n
个孩子。 Such as;如;
var n = 2;
document.querySelector(`.demo div p:nth-child(${n})`);
On the other hand CSS selector combinators are also very powerful.另一方面,CSS 选择器组合器也非常强大。 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.如果您只是想访问第一个
<p>
之后的下一个<p>
直接位于 <div> 下方,该<div>
位于带有.demo
class 的元素下方。 So ".demo > div > p + p"
should be sufficient.所以
".demo > div > p + p"
就足够了。 In this particular case we don't have any nested div
s under .demo
so we can also do like ".demo div p + p"
.在这种特殊情况下,我们在
.demo
下没有任何嵌套的div
,因此我们也可以像".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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.