1

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!!

Martin
  • 11
  • 1
  • 2
  • 2
    Have you read the (essential) warning [against regex parsing of html](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)? – David Thomas Nov 19 '10 at 23:39

3 Answers3

1

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

cambraca
  • 27,014
  • 16
  • 68
  • 99
  • I would combine the `.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. – PleaseStand Nov 20 '10 at 02:08
  • Another thing to change: ` $(this).replaceWith($(this).text().replace(/a/g, 'z'));` to `this.nodeValue = this.nodeValue.replace(/a/g, 'z');`. That avoids potential problems if the text contains valid but escaped HTML tags. – PleaseStand Nov 20 '10 at 02:11
0

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...

charly
  • 956
  • 13
  • 23
0

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");
Alex
  • 64,178
  • 48
  • 151
  • 180
  • But assuming that he wants to change all instances of the particular sequence he'd have to iterate through *every* DOM-node/tag. – David Thomas Nov 20 '10 at 01:15