-3

I'm using .html() method to add multiple images to a div.

$('#info').html('<img class="catalog/chair.jgp"/><img class="catalog/chair2.jgp"/>');

But it replaces the existing elements of the div and adds the new images/content.

How do I add the image instead of replacing the elements which already exists?

0

5 Answers 5

2

That's where .append()/.prepend() is used:

$('#info').append('<img class="catalog/chair.jgp"/><img class="catalog/chair2.jgp"/>');

and even you want to use it with .html() then you have to concatenate with the old html before replacing:

var $html = $('#info').html()+'<img class="catalog/chair.jgp"/><img class="catalog/chair2.jgp"/>'
$('#info').html($html);
Sign up to request clarification or add additional context in comments.

2 Comments

That's the type of answer I was waiting for. Covers all. Thanks. +10
You are welcome @Becky.
1

Use append() instead.

$('#info').append('<img class="catalog/chair.jgp"/><img class="catalog/chair2.jgp"/>');

Comments

1

You need to append() the HTML.

Like this.

$('#info').append('<img class="catalog/chair.jgp"/><img class="catalog/chair2.jgp"/>');

Comments

0

In plain JS

var img = document.createElement( 'img' )
img.src = 'catalog/chair.jpg'
document.getElementById( 'info' ).appendChild( img )

jQuery of course has its own confusing quirks on how to do something very standard (it probably has a shorter-hand version as well, I've no idea, I try to avoid it)

var img = $( '<img>' )
img.attr( 'src', 'catalog/chair.jpg' )
img.appendTo( '#info' )

Comments

0

just try append

unless you really know what is your doing, careful use html("")(not html())

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.