[英]Jquery Get Child DIV Within DIV
I have the following HTML code within the body:我在正文中有以下 HTML 代码:
<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...但是当我想让它返回 firstChildDiv 时,它会返回“隐藏”,我已经尝试过类似...
$("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谢谢
Your last selector你最后的选择器
$("#mainContainer :first-child").attr('id')
works fine, if you correct the typo in the HTML (see this fiddle ).如果您更正 HTML 中的拼写错误,则工作正常(请参阅此小提琴)。 It says
mainContianer
instead of mainContainer
.它说
mainContianer
而不是mainContainer
。
But, anyway, why don't you select simply by the id
, if that element has an id
?但是,无论如何,如果那个元素有一个
id
,你为什么不简单地通过id
来选择呢?
$( '#firstChildDiv' )
$('#mainContainer > div:first-child').attr('id');
Try this,试试这个,
$("#mainContianer:first-child").attr("id")
Check there is no space before ':'检查':'之前没有空格
this all return you first child of parent-- in your case replace parent by mainContianer这一切都会返回你父母的第一个孩子——在你的情况下用 mainContianer 替换父母
$('#parent').children(":first")
$('#parent').children(":first-child")
$( $('#parent').children()[0] )
$('#parent').find(":first")
$('#parent').find(":nth-child(1)")
try - Child Selector (“parent > child”) try -子选择器(“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);
});
<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>
<script language="JavaScript">
jQuery(document).ready(function($) {
$("#MY_BUTTON").click(function(event) {
$("div#PARENT_DIV").find("#CHILD_DIV").hide();
});
});
</script>
<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>
for now in 2020 with jquery it can be like:现在在 2020 年使用 jquery 它可以是这样的:
function myClickOnDiv(divPrm) {
let div=$(divPrm);
let targetElement=div.find('#my_id')
}
if say you div looks like this:如果说你的 div 看起来像这样:
<div onclick=myClickOnDiv(this)><label id="my_id"></label></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.