jQuery 计算 div 标签内 img 标签的数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17833678/
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
Count number of img tags inside a div tag
提问by aBhijit
My code goes like this.
我的代码是这样的。
<div id="some_id">
<img src="some_image.png">
<img src="some_image.png">
<div class="another_div"></div>
<div class="another_div"></div>
</div>
I want to count number of img tags inside that div element.
我想计算该 div 元素中 img 标签的数量。
I found this from a similar question on stackoverflow which returns count of all the children.
我从一个关于 stackoverflow 的类似问题中找到了这个,它返回所有孩子的计数。
var count = $("#some_id").children().length;
How do I modify this code or use some other function to count the number of img tags inside the div?
如何修改此代码或使用其他一些函数来计算 div 中 img 标签的数量?
回答by jods
Count img inside #some_div:
计算 #some_div 中的 img:
$("#some_id img").length
If you want only the direct children, not all descendants:
如果你只想要直接的孩子,而不是所有的后代:
$("#some_id > img").length
回答by Optimus Prime
Use
用
var count = $("#some_id").find('img').length;
回答by Pankucins
var count = $("#some_id img").length
Select the image tags like this.
像这样选择图像标签。
回答by Anton
Try this
尝试这个
var count = $('#some_id').find('img').length;
回答by Darius M.
Or the plain version without jQuery:
或者没有 jQuery 的普通版本:
document.getElementById("some_id").getElementsByTagName("img").length
回答by Tushar Gupta - curioustushar
use this
用这个
$("#some_id img").length
回答by Gintas K
Try to get them like this:
尝试让它们像这样:
var count = $("#some_id img").length;
回答by mara-mfa
Also (even though there are many right answers here), every of these methods in jQuery, such as children(), siblings(), parents(), closest(), etc. accept a jQuery selector as a parameter.
此外(尽管这里有很多正确的答案),jQuery 中的每个方法,例如children()、siblings()、parents()、closest()等,都接受一个 jQuery 选择器作为参数。
So doing
这样做
$("#some_id").children("img").length
$("#some_id").children("img").length
should return what you need as well.
也应该返回你需要的东西。
回答by DontVoteMeDown
回答by rescue1155
var count = $("#some_id img").length;
It will give you total length of images inside a div.
它将为您提供 div 内图像的总长度。