Are there any text selector in jquery?

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>


$('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).


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(
            for (var i= matches.length; i-->0;)
      , child, matches[i]);

findText(element, /\bWorld\b/g, function(node, match) {
    var span= document.createElement('span');
    node.parentNode.insertBefore(span, node.nextSibling);

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) 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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.