2

Firstly sorry for my english, i have code that doesnt work when I execute it on

<script language="javascript" src="/thecode.js"></script>

I put thecode.js on footer

var msg=document.body.innerHTML;
for(var i=0;i<msg.length;i++){
var tx=document.body[i].innerHTML;
tx=tx.replace(/dog/ig,'animal');
tx=tx.replace(/apple/ig,'fruit');
tx=tx.replace(/\[VIdEo\]/ig,'Video');
tx=tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
document.body.innerHTML=tx;}

I think i dont make any fault, but when i execute it, its doesnt work.
thank for your attention... :)

Reza Fahmi
  • 270
  • 4
  • 11
  • there is no need of the for loop.... also `document.body[i]` is wrong... remove the for loop and `var tx=document.body.innerHTML;` – Arun P Johny Jun 05 '15 at 05:56
  • **Also never do this as it can remove any previous added event handlers** (added using script) – Arun P Johny Jun 05 '15 at 05:56
  • Note that processing HTML with a regular expression is [*doomed to fail*](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) in weird and unexpected ways. – RobG Jun 05 '15 at 06:10

1 Answers1

2

no need to iterate body element
try this:

want to change to with that js?
i have used to make it

function addTitleToSurveyUrls() {
    var elements = document.getElementsByTagName('a');
    for(var el in elements) {
       var element = elements[el];
       var href = element.getAttribute("href");
       if(href.indexOf('survey_')>-1) {
           element.setAttribute('title', 'Some TITLE HERE');
       }
    }
}

function replaceBodyElements() {
    var tx=document.body.innerHTML;
        tx = tx.replace(/dog/ig,'animal');
        tx = tx.replace(/apple/ig,'fruit');
        tx = tx.replace(/\[VIdEo\]/ig,'Video');
        tx = tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
    document.body.innerHTML=tx;
}

window.onload = function(){
    replaceBodyElements();
    addTitleToSurveyUrls();
    // ... some another operations
};

also

document.onreadystatechange = function () {
  var state = document.readyState; 
  if(state == 'complete') {
      replaceBodyElements();
      addTitleToSurveyUrls();
  }
}​

I've used onload event because maybe document has dynamic elements and etc. so better wait while all elements get loaded and change it. or You can replace window.onload with window.document.onload

num8er
  • 18,604
  • 3
  • 43
  • 57