Reputation: 21
I am trying to iterate through the DOM using JQuery and I want to change the color of every instance of the letter m. this is what I have so far:
$(document).ready(function(){
var m = "<span style='color: red;'>m</span>"
$("body").children().each(function() {
$(this).html($(this).html().replace(/m/g, m));
});
});
The problem with this is that it also modifies the html elements like links in <href>
and <img>
I tried using
if (!$(this).is("a")) { //replace }
but that didn't work. also using .text() instead of .html() didn't work for me
Upvotes: 2
Views: 1019
Reputation: 33870
To achieve what you want, you need to have a recursive fonction. In that function, you have to check if the element is a text node. Once you have a text node, you can then replace it's content. Else, you need to call the same function with the new element.
Here the said function :
letterScanner( $('body'), 'm' )
function letterScanner( $el, letter ){
$el.contents().each( function(){
if( this.nodeType == 3 ){
$( this ).replaceWith( this.textContent.replace( new RegExp( '('+letter+'+)', 'g' ), "<span style='color: red;'>$1</span>" ) );
}else{
letterScanner( $( this ), letter )
}
} );
}
Of course, change the body
selector for the closest parent for better performance.
https://jsfiddle.net/ghb4p1p8/
Upvotes: 3