tags:

views:

109

answers:

3

Is running something like:

document.body.innerHTML = document.body.innerHTML.replace('old value', 'new value')

dangerous?

I'm worried that maybe some browsers might screw up the whole page, and since this is JS code that will be placed on sites out of my control, who might get visited by who knows what browsers I'm a little worried.

My goal is only to look for an occurrence of a string in the whole body and replace it.

+2  A: 

Definitely potentially dangerous - particularly if your HTML code is complex, or if it's someone else's HTML code (i.e. its a CMS or your creating reusable javascript). Also, it will destroy any eventlisteners you have set on elements on the page.

Find the text-node with XPath, and then do a replace on it directly.

Something like this (not tested at all):

var i=0, ii, matches=xpath('//*[contains(text(),"old value")]/text()');
ii=matches.snapshotLength||matches.length;
for(;i<ii;++i){
  var el=matches.snapshotItem(i)||matches[i];
  el.wholeText.replace('old value','new value');
}

Where xpath() is a custom cross-browser xpath function along the lines of:

function xpath(str){
  if(document.evaluate){
    return document.evaluate(str,document,null,6,null);
  }else{
    return document.selectNodes(str);
  }
}
lucideer
+1  A: 

I agree with lucideer, you should find the node containing the text you're looking for, and then do a replace. JS frameworks make this very easy. jQuery for example has the powerful :contains('your text') selector

http://api.jquery.com/contains-selector/

Java Drinker
A: 

If you want rock solid solution, you should iterate over DOM and find value to replace that way.

However, if 'old value' is a long string that never could be mixed up with tag, attribute or attbibute value you are relatively safe by just doing replace.

vava
Iterating over the entire DOM is extremely inefficient.
lucideer
It's not *that* inefficient. Not all code is run within nested loops and 10ms timers.
MooGoo