[ACCEPTED]-Jquery Get Child DIV Within DIV-jquery-selectors

Accepted answer
Score: 12

Your last selector

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

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

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

$( '#firstChildDiv' )
Score: 6
$('#mainContainer > div:first-child').attr('id');

0

Score: 2

Try this,

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

Check there is no space before 1 ':'

Score: 2

Actually, you have a typo there in your 2 html

<div id="mainContianer">

should be

<div id="mainContainer">

Then you can do

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

This uses prop rather 1 than attr, which is slower and old jQuery Syntax

Score: 1

this all return you first child of parent--in your case replace parent by mainContianer

$('#parent').children(":first") 


$('#parent').children(":first-child") 


$( $('#parent').children()[0] ) 


$('#parent').find(":first") 


$('#parent').find(":nth-child(1)") 

try 1 - Child Selector (“parent > child”)

$("div > div").attr('id')  

also try out

$("div div:first-child")
Score: 1

This is working for me....

$(document).ready(function(){
    var a =$("#mainContainer div:first-child").attr('id');
    alert(a);
});

0

Score: 1
    <html>
        <head>
            <script>
                function getDiv(){
                alert("answer = "+$('#mainContianer div:first-child').attr('id'));

                }
            </script>
        </head>
        <body>

            <div id="hidden"></div>

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

                <button onclick="getDiv()">click</button>
    </body>
<html>

0

Score: 0

SCRIPT

<script language="JavaScript">
    jQuery(document).ready(function($) { 
    $("#MY_BUTTON").click(function(event) {
                 $("div#PARENT_DIV").find("#CHILD_DIV").hide();
             });    
});
</script>

HTML CODE

<div id="PARENT_DIV">
        <h1 class="Heading">MY HTML PAGE TEST</h1>
        <br />
        <div id="CHILD_DIV">THIS IS MY CHILD DIV</div>
 </div>

    <div class="MY_BUTTONS"> 
        <a class="MySubmitButton" id="MY_BUTTON">
            <span>Test it!</span>
        </a>
     </div>

0

Score: 0

for now in 2020 with jquery it can be like:

    function myClickOnDiv(divPrm) {
        let div=$(divPrm);
        let targetElement=div.find('#my_id')
    }

if say you div 1 looks like this:

<div onclick=myClickOnDiv(this)><label id="my_id"></label></div>

More Related questions