Javascript 计数<;img>;在a<;p>;没有id或类
我想知道是否有办法计数Javascript 计数<;img>;在a<;p>;没有id或类,javascript,jquery,count,detect,Javascript,Jquery,Count,Detect,我想知道是否有办法计数 现在对您来说,它应该是: var num = $('#content img').length; alert(num); <div id="content"> <!--The number of the "empty" paragraphs changes if users add more paragraphs--> <p></p> <p></p> <
现在对您来说,它应该是:
var num = $('#content img').length;
alert(num);
<div id="content">
<!--The number of the "empty" paragraphs changes if users add more paragraphs-->
<p></p>
<p></p>
<!--These are the images I look for-->
<p>
<img src="image.jpg">
<img src="image2.jpg">
</p>
<hr>
<p>
<img src="image3.jpg">
</p>
<p></p>
</div>
下面是一个基于DOM使用Javascript的可能解决方案
$('#content').find('hr').prev('p:not([id]):not[class]').find('img').length
在
$('#content').find('hr').prev('p:not([id]):not[class]').find('img').length
function getImageCount() {
var content = document.getElementById("content"),
num = 0,
hrs;
if (content) {
hrs = content.getElementsByTagName("hr");
if (hrs && hrs.length) {
num = hrs[0].previousElementSibling.children.length;
}
}
return num;
}
alert(getImageCount());