jQuery - replace function
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!!
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
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...
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");
精彩评论