How to remove elements with whitespace?

前端 未结 5 889
暖寄归人
暖寄归人 2020-12-17 01:09

I can easily remove a tag that has no blank spaces...

$(\'h2:empty\').remove();

But, when there is a space...

&l

相关标签:
5条回答
  • 2020-12-17 01:14

    try this

    $("h2").each(function(){
       var self = $(this);
       if ( self.html().trim().length == 0 )
       {
         self.remove();
       }
    });
    
    0 讨论(0)
  • 2020-12-17 01:26

    To adapt on alex's, try this:

    $('h2').filter(function() {
        return $.trim($(this).text()).length == 0;
    }).remove();
    

    see jsfiddle.

    0 讨论(0)
  • 2020-12-17 01:33

    I don't use jQuery, but I can give a straight JavaScript solution:

    var elms = document.getElementsByTagName('h2'), l = elms.length, i;
    for( i=l-1; i>=0; i--) {
        if( elms[i].innerHTML.replace(/\s+/,"") == "") {
            elms[i].parentNode.removeChild(elms[i]);
        }
    }
    

    So just do whatever the jQuery equivalent is, I guess.

    0 讨论(0)
  • 2020-12-17 01:37

    You can match elements with only whitespace text with...

    $('h2').filter(function() {
       return ! $.trim($(this).text());
    });
    

    To remove these elements, call remove() on the returned set.

    jsFiddle.


    Alternatively, without jQuery...

    elements.filter(function(element) {
        return ! (element.textContent || element.innerText).replace(/\s+/g, '');
    });
    

    If your elements is a HTMLCollection, NodeList (or otherwise not an Array), use Array.filter(elements, fn) or turn elements into an Array with Array.prototype.slice.call(elements).

    If you didn't have to support older browsers too, you could use return ! (element.textContent || element.innerText).trim().

    To remove these, loop over the elements and use thisElement.parentNode.removeChild(thisElement).

    jsFiddle.


    Alternatively, with working with nodes only...

    var containsWhitespace = function me(node) {
        var childNodes = node.childNodes;
    
        if (childNodes.length == 0) {
            return true;    
        }
    
        for (var i = 0, length = childNodes.length; i < length; i++) {
            if (childNodes[i].nodeType == 1) {
                return me(childNodes[i]);
            } else if (childNodes[i].nodeType == 3) {
                return ! childNodes[i].data.replace(/\s+/g, '');   
            }
        }
    }
    
    elements.filter(containsWhitespace);
    

    jsFiddle.

    0 讨论(0)
  • 2020-12-17 01:38

    This will only check for one space, but works for a basic example:

    $("h2:contains(' ')").remove()
    
    0 讨论(0)
提交回复
热议问题