Jquery find all elements with text

后端 未结 2 879
天命终不由人
天命终不由人 2020-12-31 13:24

What would be the best way to scan trough all the DOM, find any element that have text and wrap it in a span class? Thanx

相关标签:
2条回答
  • 2020-12-31 14:05

    To wrap all text nodes that contain something other than just whitespace:

    $('body *').contents().filter(function() { 
        return (this.nodeType == 3) && this.nodeValue.match(/\S/); 
    }).wrap("<span />")
    

    To wrap all text nodes, including those that contain only whitespace:

    $('body *').contents().filter(function() { 
        return (this.nodeType == 3) && this.nodeValue.length > 0; 
    }).wrap("<span />")
    
    0 讨论(0)
  • 2020-12-31 14:17

    You can use .each to iterate over all elememnts:

    $('*').each(function(){
        if($(this).text())
        {
            $(this).wrapInner('<span />');
        }
    })
    

    I didn't test that piece of code but it is quite simple. All you need to learn about is .each, wrapInner and * selector. jQuery docs is pretty helpful here.

    0 讨论(0)
提交回复
热议问题