开发者

select top level nodetext is not supported with jQuery?

Whenever I needed the top level text node I must wri开发者_StackOverflowte this long story?

$("#hello").clone().children().remove().end().text();

Why is there no native function to support it ?


I'm not sure why there isn't native support. I suppose you could turn that unwieldy line of code into a plugin (there must be a better name than the one I chose):

$.fn.topNodeText = function() {  
   return $(this).clone().children().remove().end().text();
};

$(document).ready(function() {
    alert($("#blahahah").topNodeText());
});


$.fn.directText = function() {  
    return $.map(this[0].childNodes, function(n){
        return n.nodeType === 3 ? n.data : [];
    }).join('');
};

$(something).directText();

What jQuery doesn't provide directly, you can hack together and put in a plugin :)


this is a very good method to get text nodes..

getTextNodes: function( el ) {
        var nodes = [];
        if(el instanceof NodeList || el instanceof HTMLCollection ){ 
                    //perhaps a better test for an array/collection of objects is required here?
                        for( var i = 0, j = el.length; i < j; i++ ) {
                            //call this function with each item in the array/collection
                            nodes = nodes.concat( arguments.callee(el[i]));
                        }
                        return nodes;
        }
            for( var i = 0, j = el.childNodes.length; i < j; i++ ) {
            var node = el.childNodes[i];
            if( node.nodeType == 3 ) {
                //ignore whitespace
                if( /^\s+$/.test( node.nodeValue ) ) continue;
                nodes.push( Tarjemlo.trim(node.nodeValue) );
            } else {
                //call this function with this child node
                nodes = nodes.concat( arguments.callee( node ) );
            }
            }
            return nodes;
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜