Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
774 views
in Technique[技术] by (71.8m points)

jquery - How to remove elements with whitespace?

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

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

But, when there is a space...

<h2> </h2> 

...this does not work.

I tried

if ($('h2').html() == " "){
    $('h2').remove(); 
}

Also no luck. Can someone help with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...