1

I am working on the following jQuery code. Assuming I have the following HTML code sample:

<div class="my-class"> 
   <h1>Hello</h1>
</div>

With jQuery, I need add the following <img src="smiley.gif" alt="Smiley face" height="42" width="42"> immediately after the opening div my-class tag. I need to target the my-class class selector.

What I am trying to achieve is the following:

<div class="my-class">
   <img src="smiley.gif" alt="Smiley face" height="42" width="42">
   <h1>Hello</h1>
</div>

I have tried the following:

$('div.my-class').after('<img src="smiley.gif" alt="Smiley face" height="42" width="42">');

but this inserts it after the closing div tag, which is not what I am after.

halfer
  • 19,824
  • 17
  • 99
  • 186
tonyf
  • 34,479
  • 49
  • 157
  • 246

2 Answers2

1

This can be achieved with .prepend() like:

$('div.my-class').prepend('<img src="smiley.gif" alt="Smiley face" height="42" width="42">');

.after() will add the html after the closing tag of the subject element.

.append() will place it inside the div but after <h1>

Fr0zenFyr
  • 1,899
  • 2
  • 28
  • 48
0

I'd do it like this :)

$('div.my-class').prepend('<img src="smiley.gif" alt="Smiley face" height="42" width="42">');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my-class"> 
   <h1>Hello</h1>
</div>
moritzg
  • 4,266
  • 3
  • 37
  • 62