Reputation: 5056
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
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
Reputation: 17900
It should be $('#div1 .label')
and $('#div2 span')
. You need separate using space
Upvotes: 1
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
Reputation: 63512
You almost have it:
$("#div1 .label");
Selects all elements that are descendants of a given ancestor.
You could also make it more specific:
$("#div1 > .label");
Selects all direct child elements specified by "child" of elements specified by "parent".
Upvotes: 4
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