Jquery在DIV中获取子DIV [英] Jquery Get Child DIV Within DIV
问题描述
我在身体内有以下HTML代码:
< div id =hidden>
< / div>
< div id =mainContianer>
< div id =firstChildDiv>
< / div>
< / div>
我使用下面的代码来获取子元素
$(div:first-child)。attr('id')
但是,当我想让它返回firstChildDiv时,它会返回隐藏,我尝试了类似...
< code $(div [mainContainer] div:first-child)。attr('id')
$(div [id = mainContainer]:first-child)。attr ')
$(#mainContainer:first-child)。attr('id')
我知道它是一件简单的事情,但似乎无法看到我要去的地方出错......
谢谢
<您最后的选择
$(#mainContainer:first -child)。attr('id')
可以正常工作, HTML(请参阅此小提琴)。它说 mainContianer
而不是 mainContainer
。
无论如何,如果该元素的 id
?
id
$('#firstChildDiv')
I have the following HTML code within the body:
<div id="hidden">
</div>
<div id="mainContianer">
<div id="firstChildDiv">
</div>
</div>
I am using the following code to get the child
$("div:first-child").attr('id')
But this returns "hidden" when I want it to return firstChildDiv, I have tried things like...
$("div[mainContainer ] div:first-child").attr('id')
$("div[id=mainContainer ] :first-child").attr('id')
$("#mainContainer :first-child").attr('id')
I know its a simple thing to do, but cant seem to see where I am going wrong...
Thanks
Your last selector
$("#mainContainer :first-child").attr('id')
works fine, if you correct the typo in the HTML (see this fiddle). It says mainContianer
instead of mainContainer
.
But, anyway, why don't you select simply by the id
, if that element has an id
?
$( '#firstChildDiv' )
这篇关于Jquery在DIV中获取子DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!