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?
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?
That's because you're replacing the innerHTML
with the text test
. You're not appending the text.
Try:
var div = document.getElementById('candy');
div.innerHTML = div.innerHTML + 'test';
Taken from here.
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>
Use
var div = document.getElementById('candy');
div.insertAdjacentHTML('beforeend', 'test');
Reference: https://developer.mozilla.org/en/docs/DOM/element.insertAdjacentHTML
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.