jQuery: Image closing tag destroyed

I use jQuery to append an image tag.  The problem is that the closing tag for the image is destroyed!

<img /> becomes <img>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
 $('div').append('<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/Peach_flowers.jpg/287px-Peach_flowers.jpg" alt="" />');
 alert( $('div').html() );




Open in new window

LVL 16
Who is Participating?
ProculopsisConnect With a Mentor Commented:
If you insist:


    $("<img />").attr({
        src: "http://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/Peach_flowers.jpg/287px-Peach_flowers.jpg",
        alt: ""
    }).get(0).outerHTML + "</img>"



Open in new window

selvolConnect With a Mentor Commented:
In HTML the <img> tag has no end tag.

will that still work for you?

Why do you need to close the img?
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

hankknightAuthor Commented:
The document type in my example is XHTML 1.0.

I use this script to create VALID XHTML that users can copy and paste onto websites.

How can I get those closing tags in place?
Change this line to point to the attached js.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
Change to

<script type="text/javascript" src="g.js"></script>

Your end result is this.

img tag
To obtain that result I edited the ......min.js by removing the "img" parsing function for that tag.

David S.Connect With a Mentor Commented:
@Hank  What are you trying to achieve here?  Is there a particular reason that you're appending the <img> to a <div> and then displaying the <div>'s contents? Why the intermediate step?

@Selvol  What happens if Hank is using some other code that's relying on jQuery to not have that modification?
@Kravimir  "What happens if Hank is using some other code that's relying on jQuery to not have that modification?"
Should probally be a second question. As you know.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.