[ACCEPTED]-Jquery Get Child DIV Within DIV-jquery-selectors
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' )
$('#mainContainer > div:first-child').attr('id');
0
Try this,
$("#mainContianer:first-child").attr("id")
Check there is no space before 1 ':'
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
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")
This is working for me....
$(document).ready(function(){
var a =$("#mainContainer div:first-child").attr('id');
alert(a);
});
0
<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
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
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.