Skizit
Skizit

Reputation: 44852

find and replace on a HTMLelement.INNERHTML?

 var e = document.getElementById('anelement');
 e.innerHTML = f.anelement

inside anelement I'd like to replace every occurance of a certain word e.g apple with orange how would I go about doing this?

Upvotes: 0

Views: 4379

Answers (1)

Saul
Saul

Reputation: 18041

innerHTML is a String object which has the replace method:

e.innerHTML = f.anelement.innerHTML.replace("apple", "orange");

Edit

As Matt Brock pointed out in comments, a simple replace does not differentiate between whole words and substrings. A more precise solution, using regular expressions, would be:

var result = "apple to orange".replace(/\b(apple)\b/g, "orange");
// evaluates to "orange to orange"

Upvotes: 5

Related Questions