简体   繁体   中英

Change the color of one character using JQuery without changing HTML tags

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM