Valachio
Valachio

Reputation: 1135

Replacing a string in HTML element with another string

Is there some way to replace a specific string within a HTML element with another string? I tried using .replace() but there was no effect (and no error message in the console either). See code below.

month = 1
date = document.getElementById('date');
date.innerHTML = month + ' months';

if (month == 1) {
    date.innerHTML.replace('months', 'month');
}

Upvotes: 0

Views: 63

Answers (3)

Dakota
Dakota

Reputation: 525

Replace to

date.innerHTML =  date.innerHTML.replace('months', 'month');

Upvotes: 1

marcelotokarnia
marcelotokarnia

Reputation: 386

The replace method actually doesn't change the content of the string, it generates a new string with the desired changes, so you should assign it to some variable, or use it as some function parameter.

So in your case, you're just missing reassign it to the date.innerHTML like:

date.innerHTML = date.innerHTML.replace('months', 'month')

Upvotes: 2

Hoàng Trần
Hoàng Trần

Reputation: 103

It should be

month = 1
date = document.getElementById('date');
date.innerHTML = month + ' months';

if (month == 1) {
    date.innerHTML = date.innerHTML.replace('months', 'month');
}

Upvotes: 2

Related Questions