mathieu_b
mathieu_b

Reputation: 393

Insert text after an <img> tag

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

Answers (4)

Tamil Selvan C
Tamil Selvan C

Reputation: 20239

Use

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

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

Upvotes: 0

Irfan Mir
Irfan Mir

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

JJJ
JJJ

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

Charlie
Charlie

Reputation: 11787

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.

Upvotes: 6

Related Questions