简体   繁体   中英

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?

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(")"));

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"));

When you do the greatest sin of all, that is .innerHTML += (specifically innerHTML combined with += , neither of them are bad alone), what happens is:

  • Serialize the element's DOM subtree into a html string.
  • Concatenate some stuff into that html string
  • Remove all elements from the target element
  • Parse the html resulted above into a new DOM subtree. This means all the elements are new.
  • Append that into the target element

So given this, actual_button refers to a detached dom element. Not to the another img element created from parsing html.

Works if you set the image ID and get it after changing innerHTML :

var meaning = document.getElementById('meaning');
meaning.innerHTML += 'Something ...';

var actual_button = document.createElement('img');
actual_button.id = 'actual_button';
actual_button.src = 'http://www.pawelbrewczynski.tk/images/add.png';
actual_button.className = 'add_word';

meaning.appendChild(actual_button);
meaning.innerHTML += " ... and another.";

var actual_button= document.getElementById('actual_button');
actual_button.src = 'http://www.pawelbrewczynski.tk/images/loading.gif';

http://jsfiddle.net/j8yEG/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM