Javascript Jquery 在 DIV 中获取子 DIV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11468122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Get Child DIV Within DIV
提问by LmC
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
谢谢
回答by Sirko
Your last selector
你的最后一个选择器
$("#mainContainer :first-child").attr('id')
works fine, if you correct the typo in the HTML (see this fiddle). It says mainContianerinstead of mainContainer.
工作正常,如果您更正 HTML 中的错字(请参阅此小提琴)。它说,mainContianer而不是mainContainer。
But, anyway, why don't you select simply by the id, if that element has an id?
但是,无论如何,id如果该元素具有,为什么不简单地通过 进行选择id?
$( '#firstChildDiv' )
回答by Simon
$('#mainContainer > div:first-child').attr('id');
回答by Matt
Try this,
尝试这个,
$("#mainContianer:first-child").attr("id")
Check there is no space before ':'
检查 ':' 前没有空格
回答by Beat Richartz
回答by Nirmal
<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>
回答by Franquis
This is working for me....
这对我有用......
$(document).ready(function(){
var a =$("#mainContainer div:first-child").attr('id');
alert(a);
});
回答by Pranay Rana
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”)
尝试 -子选择器(“父>子”)
$("div > div").attr('id')
also try out
也试试
$("div div:first-child")
回答by Eldric Dsouza
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>

