Are there any text selector in jquery?

2019-03-01 01:00发布

问题:

Are there any text selector in jquery ?

My Code

<anything>Hello World! Hello World!</anything>

Reslut Should be (Using Jquery)

<anything>Hello <span>World</span>! Hello <span>World</span>!</anything>

回答1:

$('anything').html(function(i, v) {
    return v.replace(/(World)/g, '<span>$1</span>');
});  

The above snippet uses functionality added in jQuery 1.4.

Note: this solution is safe for elements containing only raw text (and no child elements).



回答2:

No. jQuery works primarily with elements and gives you very little for handling text.

To do a find-and-replace on text you will need to check each text node separately and do DOM splitText operations to take it apart when a match is found. For example:

function findText(element, pattern, callback) {
    for (var childi= element.childNodes.length; childi-->0;) {
        var child= element.childNodes[childi];
        if (child.nodeType==1) {
            var tag= child.tagName.toLowerCase();
            if (tag!=='script' && tag!=='style' && tag!=='textarea')
                findText(child, pattern, callback);
        } else if (child.nodeType==3) {
            var matches= [];
            var match;
            while (match= pattern.exec(child.data))
                matches.push(match);
            for (var i= matches.length; i-->0;)
                callback.call(window, child, matches[i]);
        }
    }
}

findText(element, /\bWorld\b/g, function(node, match) {
    var span= document.createElement('span');
    node.splitText(match.index+match[0].length);
    span.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(span, node.nextSibling);
});


回答3:

You can do a regex replacement, etc for your simple case, but for a more general answer: no.

jQuery just doesn't provide much help when dealing with text nodes, it's designed primarily for dealing with element node types (nodeType == 1), not text node types (nodeType == 3)...so yes you can use it where it helps (e.g. .contents() and .filter()), but that won't be often since it's not the library's main purpose.