Are there any text selector in jquery?

前端 未结 3 1430
野的像风
野的像风 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 00:56

    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.

    0 讨论(0)
  • 2021-01-25 01:07
    $('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).

    0 讨论(0)
  • 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);
    });
    
    0 讨论(0)
提交回复
热议问题