-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?

Dev
  • 212
  • 1
  • 14
Becky
  • 5,467
  • 9
  • 40
  • 73

5 Answers5

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);
Jai
  • 74,255
  • 12
  • 74
  • 103
1

Use append() instead.

$('#info').append('<img class="catalog/chair.jgp"/><img class="catalog/chair2.jgp"/>');
Kristoffer Jälén
  • 4,112
  • 3
  • 30
  • 54
1

You need to append() the HTML.

Like this.

$('#info').append('<img class="catalog/chair.jgp"/><img class="catalog/chair2.jgp"/>');
Jia Jian Goi
  • 1,415
  • 3
  • 20
  • 31
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' )
Matt Styles
  • 2,442
  • 1
  • 18
  • 23
0

just try append

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

JsonSong
  • 328
  • 2
  • 14