Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery find all elements with text

Tags:

jquery

text

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

like image 630
Mircea Avatar asked Jun 22 '10 08:06

Mircea


2 Answers

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 />")
like image 101
Mario Menger Avatar answered Sep 23 '22 01:09

Mario Menger


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.

like image 38
dzida Avatar answered Sep 20 '22 01:09

dzida