0

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?

Pointy
  • 405,095
  • 59
  • 585
  • 614
mathieu_b
  • 383
  • 1
  • 5
  • 19

4 Answers4

6

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.

Community
  • 1
  • 1
Charlie
  • 11,380
  • 19
  • 83
  • 138
  • Applying this to the OP's example markup the result will be `Insert text here!test` so it will work only once, and only if there isn't any text in the div beforehand. – JJJ May 05 '13 at 16:41
  • 2
    I assumed that the text: `Insert text here!` would be nonexistent, and then the JS would you know, insert the text there :) – Charlie May 05 '13 at 16:42
1

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>
JJJ
  • 32,902
  • 20
  • 89
  • 102
  • Is there something more "properly", I mean a function like `lastChild` ? – mathieu_b May 05 '13 at 16:35
  • Sure, `var children = document.getElementById('candy').childNodes; var lastChild = children[ children.length - 1 ];` but it's not any more "proper" than a named span. – JJJ May 05 '13 at 16:39
0

Use

var div = document.getElementById('candy');
div.insertAdjacentHTML('beforeend', 'test');

Reference: https://developer.mozilla.org/en/docs/DOM/element.insertAdjacentHTML

Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
-4

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.

Irfan Mir
  • 2,107
  • 8
  • 27
  • 33