开发者

How to remove all nontext nodes from the beginning of the contents of a div?

How can I remove the NonText Nodes(BR,empty <p> tags, nbsp) from the html of a div but only those which occur before the first text node appears. Just like stripping leading white space from a normal string of characters, but here to remove leading whitespace from the HTML string.

I have tried using Regular Expressions, but often problems occur in this approach. I would like to do it using NodeType and JQuery. If anyone has any example, please share.

Thanks!

UPDATE:

Take the following DIV:-

<div id="foo">
        <div>
            <div>
                <p>
                </p>
                <p>
                    &nbsp;
                </p>
                <br/>
                <p>
                    this is a test</p>
                <p>
                    &nbsp;
                </p>
                <br />
                <br>
                <p>
                    this is a fast test
                </p>
       开发者_如何学Python     </div>
        </div>
    </div>

When passing "foo" to the whitespace removal function, it should become like following:-

<div id="foo">
        <div>
            <div>
                <p>
                    this is a test</p>
                <p>
                    &nbsp;
                </p>
                <br />
                <br>
                <p>
                    this is a fast test
                </p>
            </div>
        </div>
    </div>


Something like this should do it:

var $contents = $('#foo').contents();
var stopFiltering = false;

$contents.filter(function() {
    var isEmpty = $.trim($(this).text()) == '' ||
                  this.tagName == "BR";
    var shouldFilter = !stopFiltering && isEmpty;
    stopFiltering = stopFiltering || !isEmpty;
    return shouldFilter;
}).remove();

This is an adaptation of the filter function. Each element (including text nodes) is tested for "emptiness" (isEmpty). After the first non-empty node is seen shouldFiltering is set to false, and this way the filtering condition expresses your requirements: select empty nodes and elements before the first non-empty one.

See it in action.

Update: Recursive solution is here. It simply packages the above into a function TrimElements and recurses into all children of the target element before processing the target element itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜