Search code examples
javascriptjqueryhtmljquery-selectors

Jquery Get Child DIV Within DIV


I have the following HTML code within the body:

<div id="hidden">

</div>

<div id="mainContianer">
    <div id="firstChildDiv">

    </div>
</div>

I am using the following code to get the child

$("div:first-child").attr('id') 

But this returns "hidden" when I want it to return firstChildDiv, I have tried things like...

$("div[mainContainer ] div:first-child").attr('id') 
$("div[id=mainContainer ] :first-child").attr('id') 
$("#mainContainer :first-child").attr('id') 

I know its a simple thing to do, but cant seem to see where I am going wrong...

Thanks


Solution

  • Your last selector

    $("#mainContainer :first-child").attr('id') 
    

    works fine, if you correct the typo in the HTML (see this fiddle). It says mainContianer instead of mainContainer.

    But, anyway, why don't you select simply by the id, if that element has an id?

    $( '#firstChildDiv' )