Swap all words in an HTML code

Asked

Viewed 919 times

2

I need to do a Javascript function that changes all the words found inside a site. I tried something like:

var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
    var txt = elements.replace("Original","Alterada");
    document.getElementsByTagName(i).element.innerHTML = txt;
}

But unfortunately it didn’t work. Several errors appear. Some solution?

1 answer

5


Thus:

var elements = document.getElementsByTagName('*');

for (var i = 0; i < elements.length; i++) {
    var txt = elements[i].innerHTML.replace("Original", "Alterada");
    elements[i].innerHTML = txt;
}

Note that this solution will only exchange the word "Original", not "original", not "ORIGINAL", etc.

Example in jsFiddle


At @Kazzkiq’s suggestion, the case-insensitive solution would look like this:

var elements = document.getElementsByTagName('*');

for (var i = 0; i < elements.length; i++) {
    var txt = elements[i].innerHTML.replace((new RegExp('(original)', 'gi')), "Alterada";
    elements[i].innerHTML = txt;
}

Example in jsFiddle

  • Friend, perfect your answer. Thank you very much.

  • 2

    For case insensitive: .replace((new RegExp('(original)', 'gi')), "alterada")

  • Thanks! I updated the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.