Reputation: 15936
I need to replace all the words in a DOM (web page in memory) using jquery and javascript. I need to transform this:
<html>
<head>
Hi to all
</head>
<body>
Hi to all
</body>
</html>
Into this:
<html>
<head>
Bye to all
</head>
<body>
Bye to all
</body>
</html>
But without modifying the tags (ONLY THE VALUES IN THERE)
One try is:
jQuery.fn.replaceEachOne = function (objective, rep) {
return this.each( function(){
$(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
}
);
}
But it continue replacing the tag values and breaks the page if I put it.
Help!!!
Upvotes: 0
Views: 1735
Reputation: 15936
Finally...
Thanks to everyone...
jQuery.fn.replaceEachOne = function (objective, reposition) {
this.contents().each(function(){
if (this.nodeType == Node.ELEMENT_NODE) {
$(this).replaceEachOne(objective, reposition);
} else if (this.nodeType == Node.TEXT_NODE) {
var label = document.createElement("label");
label.innerHTML = this.nodeValue.replace(objective, reposition);
this.parentNode.insertBefore(label, this);
this.parentNode.removeChild(this);
}
});
}
Upvotes: 0
Reputation: 41533
if you don't want it to change your tags, why do you modify the "html"and not just the text?
jQuery.fn.replaceEachOne = function (objective, rep) { return this.each( function(){ $(this).text( $(this).text().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) ); } ); }
Upvotes: 1
Reputation: 439
One way that would do it albeit inefficiently would be:
var element = document.getElementsByTagName('html')[0];
element.innerHTML = element.innerHTML.replace('Hi to all', 'Bye to all');
The 'Hi to all' in quotes can also be replaced with a regex if you want.
Upvotes: 0
Reputation: 688
Im guessing that there are going to be other elements in the header rather then just replacing everything with the new text. Try out something like this
$(function(){
var element = $('body, head').find('*:contains("Hi to all")');
element.html('Bye to all');
});
Upvotes: 1