Finding text node

前端 未结 8 1298
半阙折子戏
半阙折子戏 2021-01-03 08:14

Is there a clever jQuery selector for selecting a text node like this:

one two three
8条回答
  •  时光取名叫无心
    2021-01-03 08:45

    I'm not sure you can easily do that with straight jQuery, unless you can wrap that word in another tag when writing it out. You could resort to regular expressions, something like:

    function wrapWithTag(tagname, element, text)
    {
        var html = element.html();
        var rx = new RegExp('(' + text + ')', "gi");
    
        element.html(html.replace(rx, '<' + tagname + '>$1'));
    }
    
    $(function(){
        wrapWithTag('strong', $('div'), 'three');
    });
    

    The regular expression will need some tuning if you're trying to match text in different places within the element though.

提交回复
热议问题