Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 633
Lemex Avatar asked Jul 13 '12 09:07

Lemex


People also ask

How do I select a div inside a div?

Use document.querySelector on to select a div and then select an element within it with the given class after that. We just call querySelector on the element with the ID mydiv to select items inside that div. Therefore, innerDiv is the div with the class myclass .

How do I get inside a div in jQuery?

Projects In JavaScript & JQuery To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements.

How do you get children of children in jQuery?

$('. parents-of-all span'). addClass('hello'); Would apply the class "hello" to all <span> elements that are descendants of an element of class parents-of-all .


1 Answers

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' )
like image 82
Sirko Avatar answered Oct 02 '22 07:10

Sirko