JQuery没有看到第一个<p>,但为什么?

时间:2016-06-23 21:22:08

标签: jquery jquery-selectors

我正在使用$ .parseHTML()将字符串转换为HTML DOM对象:

var html = $.parseHTML('\
    <div class="row podcast">\
    <div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 podcast_info">\
    <h4></h4>\
    <p></p>\
    <p></p>\

剩下的不是很重要,这是导致我误解的两个<p>。还有几十个div和东西,它以')结尾;经过大约三十排。 HTML代码是可靠的,所以我不会在这里发布。

出于某些奇怪的原因,这些参考文献:

$('.podcast_info').find('p:first')
$('.podcast_info').find('p:nth-child(1)')

所有返回undefined。 jQuery不存在<p>之后的第一个<h4>。他们回复nth-child(2),下一个回复nth-child(3)

为什么?在它们之前的块中没有其他<p>。即使我将p:first输出到控制台,它也会返回undefined。那怎么样?

JQuery版本是2.2.4。

1 个答案:

答案 0 :(得分:0)

为什么p:first-childp:nth-child(1)无效?

Image

这是因为p first-child,而h4是。您可能需要:

$("p").first();

所以试试:

$('.podcast_info').find('p').first();
$('.podcast_info').find('p:nth-of-type(1)');

<强>段

&#13;
&#13;
$(function () {
  console.log($('.podcast_info').find('p').first().length);
  console.log($('.podcast_info').find('p:nth-of-type(1)').length);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row podcast">
  <div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 podcast_info">
    <h4></h4>
    <p></p>
    <p></p>
  </div>
</div>
&#13;
&#13;
&#13;