2009-12-03 29 views
37

我想编写代码来搜索所有的孩子有一个特定的类的div。 DIV没有ID。这里是我将要使用的HTML。jQuery - 找到一个特定的类的孩子

<div class="outerBUBGDiv"> 
<div class="innerBUBGDiv"> 
<div class="bgHeaderH2">Technology Group</div> 
<div class="bgBodyDiv"> 
<div align="center"> 
<img height="33" border="0" width="180" src="/heading.jpg"/> 
    /////other stuff here///// 
</div> 
</div> 
</div> 

任何想法,我怎么能得到div中的文本与类bgHeaderH2。

在此先感谢。

评论补充说,没有解释这很好最初)

+0

对不起,我没有正确解释这一点。我的$(this)是上面所有孩子的父亲,一个外部的div。我需要找到哪些孩子有一类bgHeaderH2。所以我需要做$(this).something – Caroline 2009-12-03 12:09:10

+0

看到我下面修改的答案... – Ryan 2009-12-03 12:34:00

回答

26

基于您的评论,moddify这样:

$('.bgHeaderH2').html(); // will return whatever is inside the DIV 

到:

$('.bgHeaderH2', $(this)).html(); // will return whatever is inside the DIV 

更多选择:http://docs.jquery.com/Selectors

+4

10你应该总是使用类选择器'div.bgHeaderH2 '或者会有性能损失见http://www.componenthouse.com/article-19 – 2009-12-03 12:58:01

+0

@Dave:很棒的提示!没有事件认为,因为我正在写这个:) – 2009-12-03 13:11:53

+2

这个答案是真的“找到具有特定类的页面中的任何元素。” 瑞恩的答案更适合寻找某个特定类别的孩子的问题。 – Ryan 2013-07-16 16:56:55

58
$(this).find(".bgHeaderH2").html(); 

$(this).find(".bgHeaderH2").text(); 
+0

感谢您的更新瑞安,这与1月的其他建议一样工作 – Caroline 2009-12-03 12:38:04

2

我不知道我是否正确地理解你的问题,但如果这个div是一些其他分区的孩子,应该没有问题。您可以简单地通过使用以下代码从类bgHeaderH2的所有div中获取文本:

$(".bgHeaderH2").text(); 
相关问题