Are there any text selector in jquery?

前端 未结 3 1431
野的像风
野的像风 2021-01-25 00:22

Are there any text selector in jquery ?

My Code

Hello World! Hello World!

Reslut Should be (Using Jque

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 01:08

    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);
    });
    

提交回复
热议问题