Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does innerHTML not change src of an image?

I have to set one src to an image object. Then I change it.

But if I add something to the element (content of element), such as

meaning.innerHTML += ")";

(where meaning is parent element of image), then if change the src of object it won't affect the document.

Example: http://jsfiddle.net/WcnCB/3/

Could you explain me why it happens, and how to fix it?

like image 215
Paul Brewczynski Avatar asked Dec 21 '22 17:12

Paul Brewczynski


2 Answers

meaning.innerHTML += ')'; does more than you think. Visually it just appends a ) character, but behind the scenes what happens is:

meaning.innerHTML = meaning.innerHTML + ')';

So, you're first converting the DOM to a string representation (HTML), then adding a ) character, and finally have convert it back from HTML to the DOM. All elements the HTML represents are created again, and meaning is replaced by those new elements. So your old one is distroyed.

The simplest solution is to use createTextNode: http://jsfiddle.net/WcnCB/4/.

meaning.appendChild(document.createTextNode(")"));
like image 144
pimvdb Avatar answered Jan 02 '23 07:01

pimvdb


By writing innerHTML += ... you are overwriting the previous HTML and destroying every reference to it - including the actual_button variable.

Why are you using innerHTML += ... anyway? You should be doing:

meaning.appendChild(document.createTextNode("(Something"));
like image 32
Niet the Dark Absol Avatar answered Jan 02 '23 08:01

Niet the Dark Absol