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
2010-06-22 08:29:34
Looks like there is some more work left: http://jsbin.com/oquhu3
Peter Jaric
2010-06-22 08:33:45
try to add $(document).ready(); to your code: $(document).ready(function(){$('*').each(function{}( if($(this).text()) { $(this).wrapInner('<span />'); }))})
Lukasz Dziedzia
2010-06-22 08:36:40
I think that this will add class to all HTML elements regardless if they have or not actual text.
Mircea
2010-06-22 08:38:15
@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
2010-06-22 08:43:03
OK, now it should works! thanks for the info
Lukasz Dziedzia
2010-06-22 09:20:01
@Mircea seems to be right (I tested it)... There are a lot of spans added to the DOM with this method.
Peter Jaric
2010-06-22 09:33:19
+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
2010-06-22 10:08:29
See this code in action at: http://jsbin.com/oquhu3/3 (the one *with* whitespace)
Peter Jaric
2010-06-22 10:12:14
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
2010-06-22 17:10:34
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
2010-06-22 17:15:04
Hmmm, I've did it anyway by making a variable and adding a parent class. Thanx guys.
Mircea
2010-06-22 17:49:33