简体   繁体   English

使用Jquery在父div中选择孙子

[英]Select grandchildren inside a parent div using Jquery

Below is the code I am working with, as you can see, there is an id named "parent" and an id named "grandchilden". 下面是我正在使用的代码,正如您所看到的,有一个名为“parent”的id和一个名为“grandchilden”的id。 My goal is to get the content inside of this div "grandchildren". 我的目标是获得这个div“孙子”的内容。 How can I achieve it? 我怎样才能实现它?

I've tried $(this).closest('.grandchildren') , but didnt work. 我试过$(this).closest('.grandchildren') ,但没有用。

<div id="parent">
  <a href="#">
    <div>
      <p id="grandchildren">
        This is a content
      </p>
    </div>
  </a>
</div>

If you have a ID on that div you can use $('#grandchildren').html() 如果您在该div上有ID,则可以使用$('#grandchildren').html()

If you don't have a ID for it, what is the pattern? 如果您没有ID,那么模式是什么? div > a > div > p ? div > a > div > p In that case you can use this: 在这种情况下,您可以使用此:

$('div#parent > a > div > p').html();

Demo here 在这里演示

Please notice the difference between .text() and .html() , if you just need to get text use .text() instead of .html() 请注意.text().html()之间的区别,如果你只需要使用.text()代替.html()

If you have a reference like this you could use find which searches downwards, with the selected element as starting point: 如果你有这样一个参考this ,你可以使用find ,其搜索向下,与作为起点选定的元素:

$(this).find('.someClass')
$('#parent').find('#grandchildren').text();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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