0

I would like to know how I can have more then one ID and one class in one jQuery statement. So let's say I have this one:

<div id="content1">
    <div id="names">
        <div class="subheader">
            Other names
        </div>
        <div class="subtext">
        </div>
    </div>
    <div id="age">
        <div class="subheader">
            Age
        </div>
        <div class="subtext">
        </div>
    </div>
</div>
<div id="content2">
    <div id="names">
        <div class="subheader">
            Other names
        </div>
        <div class="subtext">
        </div>
    </div>
    <div id="age">
        <div class="subheader">
            Age
        </div>
        <div class="subtext">
        </div>
    </div>
</div>

How can I now do something like:

$("#content #names.subtext").html("some name");

I also tried to use names and age as class. But there I have the same trouble. So is this issue really one or how should that usually be solved instead?

kwoxer
  • 3,734
  • 4
  • 40
  • 70

3 Answers3

1

You can use .find

$('#content').find('#names').find('.subtext').html('foo');
Tyranicangel
  • 189
  • 2
  • 16
1

As IDs must be unique, you will have to use classes instead:

<div id="content1">
    <div class="names">
        <div class="subheader">
            Other names
        </div>
        <div class="subtext">
        </div>
    </div>
    <div class="age">
        <div class="subheader">
            Age
        </div>
        <div class="subtext">
        </div>
    </div>
</div>
<div id="content2">
    <div class="names">
        <div class="subheader">
            Other names
        </div>
        <div class="subtext">
        </div>
    </div>
    <div class="age">
        <div class="subheader">
            Age
        </div>
        <div class="subtext">
        </div>
    </div>
</div>



$(".names .subtext").html("some name");
o--oOoOoO--o
  • 770
  • 4
  • 7
1

If the elements are direct childs of your content you can use the child-selector of css:

$('#content > #names > .subtext').html('some name');

Demo

empiric
  • 7,825
  • 7
  • 37
  • 48
  • Indeed that's even shorter. But could you tell me if there is a difference to `$('#content #names .subtext').html('some name');` because is also working. – kwoxer Mar 03 '15 at 14:14
  • `x > y` matches direct child of the parent elemtent, whereas `x y`matches when an element y is an arbitrary descendant. Have a look [here](http://stackoverflow.com/q/1182189/4202224). So because of the specification, the child selector is going to be faster on large sites – empiric Mar 03 '15 at 15:14