can I select #id > #id with jQuery?
I've got this structure
<div id="slide1">
<div id="slide_body">
some content
</div>
</div>
<div id="slide2">
<div id="slide_body">
some content
</div>
</div>
Is there a way to select, using jquery, only the #slide_body inside #slide1?
Or is the only solution to append the id to each body div like
<div id="slide2">
<div id="slide_2_slide_body">
some content
</div>
</div>
The answer to the first question:
can I select #id > #id with jQuery?
You can infact do that exact syntax $('#slide1 > #slidebody')
. The >
character means direct descendant and is called the child selector (http://api.jquery.com/child-selector/). If the element may not be a direct descendant but nested inside something else you would omit the >
and end up with $('#slide1 #slidebody')
.
As for the HTML snippet most are correct in mentioning that it is bad to have the same id on different elements and is considered an invalid document.
http://jsfiddle.net/infiniteloops/LzFAr/
You can't use unique IDs in one document
This attribute assigns a name to an element. This name must be unique in a document.
http://www.w3.org/TR/html401/struct/global.html#h-7.5.2
In your example you may use class "slide_body"
<div id="slide1">
<div class="slide_body">
some content
</div>
</div>
And then you can select it with #slide1 .slide_body
or $("#slide1").find('.slide_body')
Use
$('#slide1 > #slide_body')
Your markup is invalid. You cannot have two elements with the same ID. For this reason, the answer is no. Use classes instead.
<div id="slide1">
<div class="slide_body">
some content
</div>
</div>
<div id="slide2">
<div class="slide_body">
some content
</div>
</div>
$('#slide2>.slide_body');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With