Deepak Kumar
Deepak Kumar

Reputation: 221

How to select the first child node of a parent?

I have HTML structured like so:

<li class="mktFormReq mktField">
    <label>Industry</label>
    <span class="mktInput">
        <div class="jqTransformSelectWrapper" style="z-index: 9; width: 210px;">
            <div>
                <span style="width: 154px;">Consumer Packaged Goods</span>
                <a href="#" class="jqTransformSelectOpen"></a>
            </div>
            <ul style="width: 208px; display: none; visibility: visible;">
                <li style="">
                    <a href="#" index="0" class="">Industry*</a>
                </li>
                <li>
                    <a href="#" index="1">Business Services</a>
                </li>
                <li>
                    <a href="#" index="2" class="selected">Consumer Packaged Goods</a>
                </li>
                <li>
                    <a href="#" index="3">Energy</a>
                </li>
            </ul>
            <select class="mktFormSelect mktFReq jqTransformHidden required" name="Download_Industry__c" id="Download_Industry__c" size="1" tabindex="8" style="">
                <option value="" selected="selected">Industry*</option>
                <option value="Business Services">Business Services</option>
                <option value="Consumer Packaged Goods">Consumer Packaged Goods</option>
                <option value="Energy">Energy</option>
            </select>
        </div>
        <span class="mktFormMsg"></span>
    </span>
</li>

Here I have to pick the value in span of first div using jQuery. But when using the name or id attribute of the select element, i.e. using #Download_Industry__c, I have to pick the "Consumer Packaged Goods" value (the top span with the style attribute).

My approach is to pick the parent node of select, then select the first child, and then proceed. But I am unable to write syntax for it. I tried this way:

$('#Download_Country__c').parent().first().html();

But it's not working.

Upvotes: 0

Views: 108

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44087

Go up to the parent, then find the span you want:

$("#Download_Country__c").parent().find("div > span");

You could also use siblings:

$("#Download_Country__c").siblings(":first-child").find("span");

Upvotes: 2

K&#233;vin Bibollet
K&#233;vin Bibollet

Reputation: 3623

You are currently selecting only the parent. ($('#Download_Country__c').parent().first().html(); is the same as $('#Download_Country__c').parent().html();)

Try this for getting the first children:

$('#Download_Country__c').parent().children().first().html();

Upvotes: 2

Related Questions