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
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 .
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.
$('. 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 .
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' )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With