Pierce McGeough
Pierce McGeough

Reputation: 3086

How can I find the first id within a div

I am trying to create script that needs the id from this form. I want to find the first id within the otf_itm class. So in this case I am looking for town_id to be returned. I have tried a few different selections but so far they all have come back undefined

$('.otf_itm:first-child').attr('id');
$('.otf_itm').find('id');
$('.otf_itm').find().attr('id');

 

<div class="otf_itm">
    {if $towns|@count gt 0}
    <select class="form-control chosen add_town" name="town_id" id="town_id" data-rule-required="true" data-placeholder="Choose a town">
        <option value=""></option>
        {foreach $towns as $town}
        <option value="{$town.id}" {if $town.id eq $form_data.town_id}selected="selected"{/if}>{$town.town_name}{if $town.region_name}, {$town.region_name}{/if}</option>
        {/foreach}
        <option value="ADD_NEW">Add new town...</option>
    </select>
    {else}
    <p class="mt5">You have no towns configured.</p>
    <p class="mt5"><a href="#modal-1" role="button" id="town_id" class="showhouse-text" data-toggle="modal">Add new town</a></p>
    {/if}
</div>

Upvotes: 1

Views: 71

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

Use this:

$('.otf_itm [id]:first-child').attr("id")

Of course the above works when your templating language is correctly rendering it to a valid html output.

Upvotes: 2

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

// selects elements with an id attribute within the .otf_itm element:
$('.otf_itm [id]')
// retrieves the first:
.first()
// gets the id property from that jQuery object:
.prop('id');

Or:

// selects elements with an id attribute within the .otf_itm element:
$('.otf_itm [id]')
// retrieves the first:
.eq(0)
// gets the id property from that jQuery object:
.prop('id');

References:

Upvotes: 2

Related Questions