数& lt; img>在<p>没有id或类

Count <img> within a <p> with no id or classes

本文关键字:没有 id 或类 img lt      更新时间:2023-09-26

我想知道是否有一种方法可以在没有id或类的<hr>标签之前计算用户上传的<img>标签。

下面是目前为止的代码:
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来说,它应该是:

$('#content').find('hr').prev('p').find('img').length
$('#content').find('hr').prev('p:not([id]):not[class]').find('img').length

这是一个基于你的DOM使用Javascript的可能的解决方案

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());
在jsfiddle