简体   繁体   English

使用jquery / javascript检查是否存在任何子节点

[英]Check if any childnodes exist using jquery / javascript

I have a DOM structure with div, p and span tags. 我有一个带有div,p和span标签的DOM结构。 I want to count the 'p' tags with children nodes and that without any children. 我想用子节点计算'p'标签,没有任何子节点。 I read a solution in this forum, but it doesn't work for me: How to check if element has any children in Javascript? 我在这个论坛上阅读了一个解决方案,但它对我不起作用: 如何在Javascript中检查元素是否有子节点? . Fiddle demo 小提琴演示

$('#test').blur(function(){
    var test= $('.check p').filter(function (){
    if ($(this).childNodes.length > 0)
        return this
    });
    alert(test.lenght)
})

it should be 它应该是

$('#test').blur(function(){
    var test= $('.check p').filter(function (){
        return this.childNodes.length > 0; // as HMR pointed out in the comments if you are looking for child elements then $(this).children().length will do
    })

    alert(test.length)
})

Demo: Fiddle 演示: 小提琴

Did you try this ? 试过这个吗?

$('p:empty')

Should select all your empty p tags. 应该选择所有空的p标签。

$('p').not(':empty')

Should select all your non empty p tags. 应该选择所有非空p标签。

Here: http://jsfiddle.net/QN3aM/9/ 这里: http//jsfiddle.net/QN3aM/9/

$('#test').blur(function () {
    var test = $('.check p').filter(function () {
        return ($(this).children().length)
    });
    alert(test.length);
})

You just need to return true within filter, 0 is a falsey value and anything else will be truthy. 你只需要在过滤器中返回true ,0是一个假值,其他任何东西都是真的。 also you spelt length wrong. 你也拼错了长度。

childNodes is a property of an element. childNodes是元素的属性。 as you were converting the element into a jquery object, you'd have to use the jquery method children() 当你将元素转换为jquery对象时,你必须使用jquery方法children()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM