简体   繁体   中英

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?

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.

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