BAD_SEED
BAD_SEED

Reputation: 5056

JQuery - get element through id and then through class selector

I have something like this

<div id="div1">
   <span class="label">some text</span>
</div>
<div id="div2">
   <span class="label">some text</span>
</div>

I want to select a given span through id and then throu class. Something like #div1.label or #div2.span but this way doesn't work. How I can?

Upvotes: 9

Views: 11328

Answers (6)

Ahmad
Ahmad

Reputation: 1

This simple code worked for me $('#prettyId > label');

Upvotes: 0

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66921

#div1.label or #div2.span

You are thinking of it wrong, in your selectors you are grabbing, ID of div1 with a class of div1.label. (Which is not the way your HTML is structured, and what you are looking for)

You need these to be:

$('#div1 .label');
$('#div2 .label');

The space inbetween is just as in CSS syntax in that it looks for a child element, which in this case needs a class of label (you could also put in span.label for even more specificity)

If you want it to be more vague and capture all the divs with a span.label inside of them you could do:

$('div span.label'); // this would capture all of them
$('div[id^="div"] span.label'); // assuming they all start with the ID "div" then a #

Upvotes: 1

Muthu Kumaran
Muthu Kumaran

Reputation: 17900

It should be $('#div1 .label') and $('#div2 span'). You need separate using space

Upvotes: 1

noj
noj

Reputation: 6759

Use a space to indicate the element is a child:

$('#div1 .label');
$('#div2 span');
$('#div2 span.label');

#div1.label would select an element with id div1 and a class of label.

Upvotes: 16

hunter
hunter

Reputation: 63512

You almost have it:

$("#div1 .label");

Descendant Selector

Selects all elements that are descendants of a given ancestor.


You could also make it more specific:

$("#div1 > .label");

Child Selector

Selects all direct child elements specified by "child" of elements specified by "parent".

Upvotes: 4

Claudio Redi
Claudio Redi

Reputation: 68400

You could do

$("#div1 span.label")

if you use #div1.label you're actually selecting an element with id div1 AND having the class label.

Upvotes: 4

Related Questions