How do i make a jQuery code that replaces only text in a .HTML document and not the html-tags.
Lets say that i want to replace all "b" characters to "c" in the html code. Then i don't want that the html code is replaced.
<b>bbbbb</b>
I mean that when replacing it should be only:
<b>ccccc</b>
So that the b in the html code isn't replaced.
Thanks in advance!!
-
2Have you read the (essential) warning against regex parsing of html?David Thomas– David Thomas2010年11月19日 23:39:43 +00:00Commented Nov 19, 2010 at 23:39
3 Answers 3
Try this: (replaces a with z everywhere inside an element with id="main")
$('#main, #main *').contents().each(function() {
if (this.nodeType == 3)
this.nodeValue = this.nodeValue.replace(/a/g, 'z');
});
You could change the first bit to $('*'), but that is risky and probably slow, and on this test you can see it changes the stuff in the <style> that is generated by jsfiddle (so it probably will do the replace inside all <script>s too).
Note that the nodeType == 3 thing is telling jQuery to return only text elements. You have to use 3 instead of the constant Node.TEXT_NODE because IE 7 doesn't recognize it. (surprise surprise..)
edited to reflect idealmachine's suggestions
2 Comments
.filter part into the function passed to .each using an if statement. It should be a bit faster that way because then you would not be iterating over each text node twice.this.nodeValue = this.nodeValue.replace(/a/g, 'z');. That avoids potential problems if the text contains valid but escaped HTML tags.if you use the body selector and take like all the children it should work... I don't really know jquery but I think you just use it wrong ... It's not normal that it changes the tags... Use the DOM hierarchy it's the main tool of Javascript...
Comments
If you wanna replace text of tags in an html document and you have jQuery, don't run through the entire document and replace, use jQuery's great functions for grabbing the text and innerHTML out of elements.
For example, to replace the text of all <b> tags on the current page you could do something like this:
$("b").text("Text that will replace current text");