admin管理员组

文章数量:1362778

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.

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.

Share Improve this question asked Jul 23, 2010 at 16:54 MB.MB. 4,22112 gold badges55 silver badges82 bronze badges 1
  • I'm not 100% positive, but wouldn't this also remove any event handlers bound to the HTML elements in the body? I mean, it might be smart enough to not reparse the entire body again, but what if the body has a <script> tag in it? Its worth testing at least... jsfiddle/KMFX2 -- in FF at least - the <script> doesn't seem to run again... – gnarf Commented Jul 23, 2010 at 17:13
Add a ment  | 

3 Answers 3

Reset to default 6

Definitely potentially dangerous - particularly if your HTML code is plex, 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);
  }
}

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./contains-selector/

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.

本文标签: javascriptHow safe is it use documentbodyinnerHTMLreplaceStack Overflow