javascript(dom)nth-chld()返回null?

时间:2018-03-16 18:40:25

标签: javascript html dom

<!--This is in in the body section.--!>
<div id="par">
<p id="p1"><h3>paragraphs</h3>/p>
<p id="p2">paragraph 1</p>
<p id="p3">paragraph 2</p>
<p id="p4">paragraph 3</p>
<p id="p5">paragraph 4</p>
</div> 

<script type="text/javascript">

var x = document.querySelector("#div11 p:nth-child(2)");
document.write(x);

</script>

此html代码返回null。但是,当我删除&lt; H3&GT;第一段中的标签。 有人可以解释一下它为什么会这样做吗?

2 个答案:

答案 0 :(得分:2)

使用<p>标记内的块元素无效,因此将其更改为例如一个span并且它有效(并为id使用正确的div)。

Stack snippet

var x = document.querySelector("#par p:nth-child(2)");
console.log(x.outerHTML);
<div id="par">
  <p id="p1"> <span>paragraphs</span> </p>
  <p id="p2">paragraph 1</p>
  <p id="p3">paragraph 2</p>
  <p id="p4">paragraph 3</p>
  <p id="p5">paragraph 4</p>
</div> 

答案 1 :(得分:0)

利用querySelectorAll获取所有匹配项:

&#13;
&#13;
var x = document.querySelectorAll("div p:nth-child(2)");

console.log(x);
&#13;
<!--This is in in the body section.--!>
<div id="par">
  <p id="p1"><h3>paragraphs</h3>/p>
  <p id="p2">paragraph 1</p>
  <p id="p3">paragraph 2</p>
  <p id="p4">paragraph 3</p>
  <p id="p5">paragraph 4</p>
</div>
&#13;
&#13;
&#13;