2

I'm trying to add images dynamically in a div element. So I have a block like that

<div id="gallery" >
    <img src="images/slide1.jpg" alt="Slide 1 />
    <img src="images/slide2.jpg" alt="Slide 2 />
    <img src="images/slide3.jpg" alt="Slide 3 />
    <img src="images/slide4.jpg" alt="Slide 4 />
</div>

The idea is to insert image dynamically after the first image so my new image goes after the first image. I tried appendTo, append , after, insertAfter .

Do you have any ideas ? Thanks in advance :)

Simon
  • 1,191
  • 1
  • 18
  • 38

2 Answers2

6

You have some malformed HTML there- I'm going to assume it was a mistake when copying the code...

Perhaps this will help -

$('<img src="foo.jpg" />').insertAfter("#gallery > img:first");

If you want to use the insertAfter() function, you have to be sure that you have selected the correct element. In this case it is

  • the first img tag - :first
  • in the first level of children >
  • in the element with an id of gallery. - $("#gallery")
Lix
  • 47,311
  • 12
  • 103
  • 131
  • 1
    @roko - caught it 1sec before me! At least give me the 5min grace edit time ;) Thanks! – Lix Jul 22 '12 at 20:34
  • Thanks you, my problem is solved by an other way. Problem of conception so I resolved it by myself but your answer really really helped ! Thanks you so much ! – Simon Jul 22 '12 at 20:34
  • 1
    @Simon it would be really nice to know (and for future generations also:) **How did you do it?** And still, I'd accept this answer... – Roko C. Buljan Jul 22 '12 at 20:37
0

There is the answer to my problem, I resolved it by using this line :

$image.insertBefore("#container > img:last");

I remember that I add my pictures by the end and no the beginning of the container element.

Thanks again.

Simon
  • 1,191
  • 1
  • 18
  • 38