Get all elements without child node in jQuery

前端 未结 4 580
忘掉有多难
忘掉有多难 2020-11-27 19:33

I need to select elements without child node (including text since in

text is a child node).

I used empty, but it also consider

相关标签:
4条回答
  • 2020-11-27 20:00

    Try this

    $("span").each(function(){
    if($(this).text().trim()=='')
    $(this).text('Empty');
    });
    

    If you don't like each function then

    $("span").html(function(){
    if($(this).text().trim()=='')
    return 'Empty';
    });
    
    0 讨论(0)
  • 2020-11-27 20:08

    How about

    $("span:not(:has(*))")
    

    Selects all spans that have no children.

    Explanation

    The :has() selector "selects elements which contain at least one element that matches the specified selector." The wildcard * means all elements.

    The expression $('div:has(p)') matches a <div> if a <p> exists anywhere among its descendants, not just as a direct child.

    The :not() selector "selects all elements that do not match the given selector."

    In this case, :has() selects everything and then we use :not() to find the elements that don't match "everything"... in other words, nothing.

    Demo

    0 讨论(0)
  • 2020-11-27 20:08

    I think you can try this:

    $('span').filter(function() {
       return !this.innerHTML.replace(/\s/g,'').length;
    });
    

    DEMO

    0 讨论(0)
  • 2020-11-27 20:12
    $.expr[":"]["no-children"] = function( elem ) {
        return !elem.firstChild || !$.trim(""+ elem.firstChild.nodeValue);
    };
    $("span:no-children").html("this was empty");
    

    http://jsfiddle.net/k5eTS/6/

    There was a surprising "feature" with jQuery's $.trim that converts null to "" while I was expecting "null". Converting to string manually fixes this.

    0 讨论(0)
提交回复
热议问题