0

Is it possible to insert an img after a div with jquery? If so how to control its position?

Please try your answer here: http://jsfiddle.net/cPtU9/2/

HTML:

<div id="grey"></div>

CSS:

#grey {
    position: absolute;
    top: 50px; left: 50px;
    width:200px; height: 200px;
    background-color: #eee;
}

JQuery:

$('#grey').after("<img src='http://www.w3.org/html/logo/downloads/HTML5_Badge_128.png' />"); 
Nrc
  • 9,577
  • 17
  • 67
  • 114

4 Answers4

2

Not sure what you are trying to accomplish here. Right now the image is created right after the div...i.e outside the div. If thats intentional, you can do the following css to change the image layout:

#grey{
    position: relative; /*<-- changed to relative*/
    top: 50px;
    left: 50px;
    width: 200px;
    height: 200px;
    background-color: #eee;
}

img{
    position: relative;
    /* additional css goes here */
}

If you are trying to put the image inside the div element then you can use the prepend as follows:

$('#grey').prepend('<img src='http://www.w3.org/html/logo/downloads/HTML5_Badge_128.png' />');
kebin
  • 163
  • 5
  • Or `$('#grey').after("");` – VeeeneX Aug 02 '14 at 16:13
  • 1
    @VeeeneX: Just to be clear. **'after'** will put the image **outside** the div container whereas **'prepend'** will put the image **within/inside** the div container. – kebin Aug 02 '14 at 16:24
1

check here Fiddle

#grey {
    position: relative;
    width:200px; height: 200px;
    background-color: #eee;
}

Positioning absolute will create problem in positioning, Prefer using relative instead.

I have done it, Glad if it works.

Anyways Happy Coding!!!

Ayush Ghosh
  • 487
  • 2
  • 10
0

Use insertAfter like this &('element').insertAfter('#grey');

Jordan
  • 2,393
  • 4
  • 30
  • 60
  • Not sure but I always try a few different ways to see if it's something with the way I was trying to use it – Jordan Aug 02 '14 at 16:00
  • You can try it yourself with the link I provide. I think it does not work: http://jsfiddle.net/cPtU9/3/ – Nrc Aug 02 '14 at 16:03
0

Not sure but try

$( "<img src='http://www.w3.org/html/logo/downloads/HTML5_Badge_128.png' />" ).insertAfter( "#grey" );
Puttzy
  • 156
  • 1
  • 3
  • 13
  • Nah I get ya. When you add an element as absolute it basically removes the block level element and puts it where you tell it. Read the answer here for more details from someone that explains it much better than me: http://stackoverflow.com/questions/10092861/how-to-place-a-relative-element-after-an-absolute-element-and-cause-parent-div-t – Puttzy Aug 02 '14 at 16:25