How safe is it to use document.body.innerHTML.replace?

It starts something like:

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

dangerously?

I'm worried that maybe some browsers might mess up the whole page, and since this is JS code that will be hosted on sites beyond my control, who can get there, who knows which browsers I'm a little worried about.

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

+5
source share
3 answers

- , HTML- , - HTML- (.. CMS javascript). , , .

node XPath, .

- ( ):

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');
}

xpath() - - xpath :

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

lucideer, node , , . JS . , jQuery : (' ')

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

+3

, DOM , .

However , if the "old value" is a long string that can never be mixed with a tag, attribute, or attbibute value, you are relatively safe just by replacing.

0
source

All Articles