tags:

views:

44

answers:

2

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

A: 

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.

Lukasz Dziedzia
Looks like there is some more work left: http://jsbin.com/oquhu3
Peter Jaric
try to add $(document).ready(); to your code: $(document).ready(function(){$('*').each(function{}( if($(this).text()) { $(this).wrapInner('<span />'); }))})
Lukasz Dziedzia
I think that this will add class to all HTML elements regardless if they have or not actual text.
Mircea
@Dzida: yes, how silly of me. But you have other errors in your code, you have switched {} an () in your anonymous function... When that is fixed it seems to work.
Peter Jaric
OK, now it should works! thanks for the info
Lukasz Dziedzia
@Mircea seems to be right (I tested it)... There are a lot of spans added to the DOM with this method.
Peter Jaric
+3  A: 

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 />")
Mario Menger
See this code in action at: http://jsbin.com/oquhu3/3 (the one *with* whitespace)
Peter Jaric
Thanx, it works! I've tryed to add a class but it did not work.$(function() { $('body *').contents().filter(function() { return (this.nodeType == 3) }).addClass("someclass");});Any idea why?Thanx again.
Mircea
You can't add a class to a text node. Try wrapping it with a span that has a class: $('body *').contents().filter(function() { return (this.nodeType == 3) }).wrap("<span class='someclass' />")
Mario Menger
Hmmm, I've did it anyway by making a variable and adding a parent class. Thanx guys.
Mircea