Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I select #id > #id with jQuery?

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>
like image 859
Matt Welander Avatar asked Jan 23 '13 10:01

Matt Welander


4 Answers

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/

like image 116
Gary.S Avatar answered Oct 12 '22 21:10

Gary.S


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')

like image 35
Larry Cinnabar Avatar answered Oct 12 '22 21:10

Larry Cinnabar


Use

$('#slide1 > #slide_body')
like image 36
Vandana Avatar answered Oct 12 '22 19:10

Vandana


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');
like image 23
Paul Fleming Avatar answered Oct 12 '22 21:10

Paul Fleming