Reputation: 393
I try to insert text after an <img>
tag using javascript.
<div id="candy"><img src="candy.png" /> Insert text here!</div>
If I use document.getElementById('candy').innerHTML = "test";
the image disappears.
Can you help me?
Upvotes: 0
Views: 3848
Reputation: 20239
Use
var div = document.getElementById('candy');
div.insertAdjacentHTML('beforeend', 'test');
Reference: https://developer.mozilla.org/en/docs/DOM/element.insertAdjacentHTML
Upvotes: 0
Reputation: 2175
That is because you javascript changes the html inside the <img>
tag to test. This doesn't work as <img />
is a self-closing tag.
I believe you could you jQuery to do what you are trying to however.
Upvotes: -4
Reputation: 33153
Well, the img tag is part of the HTML inside the div, and if you replace the div's HTML you rewrite the img tag as well.
Perhaps you wanted something like this instead:
<div><img src="candy.png" /> <span id="candy">Insert text here!</span></div>
Upvotes: 1