Delebrin
Delebrin

Reputation: 1059

How do I select a child element by ID with jQuery?

I'm having trouble selecting the text inside a span element that resides in another container.

The situation I'm trying to solve is on the page we might have 10-15 different addresses at a time (so I'm appending a record Id onto the div's ID when the page is created). I need to be able to select a specific one by an ID, and then find the individual address pieces inside it.

An example of the HTML Output would be as follows:

<div id="Address_1">
    <span id="Address">Some Address</span>
    <span id="City">Some City</span>
    <span id="State">Some State</span>
    <span id="Zip">Some Zip</span>
</div>

<div id="Address_2">
    <span id="Address">Some Address</span>
    <span id="City">Some City</span>
    <span id="State">Some State</span>
    <span id="Zip">Some Zip</span>
</div>

I've tried using the following (and many, many variations):

$("#Address_" + Id).children().find("#Address").text;
$("#Address_" + Id).find("span#Address").text;
$("#Address_" + Id).find("span").find("#Address").text;

(I also can use a class inside the spans instead of a ID, but I'd like to know how to do it by ID as well.)

I'm sure it's something very simple that I'm doing incorrectly but I can seem to figure it out. I've searched a lot of questions on here as well looking for a similar one but I can't seem to find what I'm looking for. I apologize in advance if I simply didn't search using the right phrasing.

Any and all help is very much appreciated.

UPDATE: Here is my solution, thanks to the help of Ken Redler.

<div id="Address_1">
    <span class="Address">Some Address</span>
    <span class="City">Some City</span>
    <span class="State">Some State</span>
    <span class="Zip">Some Zip</span>
</div>

$("#Address_" + Id).find("span.Address").text();

Upvotes: 8

Views: 15786

Answers (1)

Ken Redler
Ken Redler

Reputation: 23943

IDs must be unique across the whole document. You should make the "inner" IDs classes instead. Then you'd have:

$('#Address_'+Id).find('span.address').text();

As per LarsH's comment, in your document, where you have:

<div id="Address_1">
    <span id="Address">Some Address</span>

you'd change it to:

<div id="Address_1">
    <span class="Address">Some Address</span>

If there's more than one of a particular ID, your results will be unpredictable at best.

Upvotes: 10

Related Questions