Paul Li
Paul Li

Reputation: 9

Can't use document.getElementById().innerHTML to rewrite the original html

I am tring to add some content after the original content, but the new content will cover the original content everytime...What wrong in this case? (Sorry for my terrible english...)

var originaltext = document.getElementById("id").innerHTML;
document.getElementById("id").innerHTML = originaltext + "newtext";

One more thing,I tried to use alert to show the "originalltext", but it have nothing to show.

alert(originaltext);

Upvotes: 0

Views: 227

Answers (3)

kayo
kayo

Reputation: 642

this problem usually occurs when the rest of your code is poorly written and contains errors or when the same ID is used several times. I had the same problems in the past.

you have tow options:

  1. check the rest of your code (validate)
  2. use jQuery - I don't know how, but it works every time.

Upvotes: 0

gdyrrahitis
gdyrrahitis

Reputation: 5978

A simple and fast way to do this is to concatenate the old value with the new.

document.getElementById('myid').innerHTML += " my new text here"

Upvotes: 0

Tiberiu Petcu
Tiberiu Petcu

Reputation: 852

your code looks ok to me. I made a jsfiddle for you just to see that it works http://jsfiddle.net/3mqsLweo/

var myElement = document.getElementById('test');
var originalText = myElement.innerHTML.toString();
myElement.innerHTML = originalText+" new text";

check that you only have one element with the id "cartzone"

Upvotes: 1

Related Questions