简体   繁体   中英

Check if any childnodes exist using jquery / javascript

I have a DOM structure with div, p and span tags. I want to count the 'p' tags with children nodes and that without any children. I read a solution in this forum, but it doesn't work for me: How to check if element has any children in 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').not(':empty')

Should select all your non empty p tags.

Here: 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. also you spelt length wrong.

childNodes is a property of an element. as you were converting the element into a jquery object, you'd have to use the jquery method children()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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