XHTML DOM manipulation with jQuery

I am using Firefox 3.5. My doctype is XHTML 1.0 Strict. Say I want to insert an image into a div with id "foo"; then I can try:

var foo = $('#foo');
foo.html('<img src="bar.gif" />');

It really adds an image. But I noticed that this led to some odd behavior later in the document, which I suspected could be caused by the ruin of XHTML. Of course, using the web developer tool for Firefox, I checked the generated source and was horrified to find that after the script works, I have:

<div id="foo"><img src="bar.gif"></div>

Where did the slash on the img! Tag end? Searching around, I found that this is not a jQuery specific issue: pure JavaScript code

document.getElementById('foo').innerHTML = '<img src="bar.gif" />';

gives the same results. So what should I do? It should be noted that the use of the extended form

<img src="bar.gif"></img>

. XHTML JavaScript?

+5
4

, , , , XHTML, HTML XHTML. : MIME text/html /xhtml + xml?

, , , , XML ( XHTML MIME)...

http://www.xml.com/pub/a/2003/03/19/dive-into-xml.html

.

+5

:

var image = document.createElement('img');
image.setAttribute('src', 'bar.gif');
foo.appendChild(image);
+2

,

:

$('input.clone').live('click', function(){

    var img = $('<img/>').attr({src : 'http://www.bennadel.com/resources/uploads/jquery_gradient_example_no_gradient.jpg'});
    $('#target').append(img);

});

HTML:

<div id="target"> test </div>
<input type="button" class="clone" id="btnClone" value="clone"/>

@pastebin

+1

try slipping away from your slash ... it is possible that it does not put it because it is not escaping:

$('#foo').html('<img src="bar.gif" \/>');

also do not forget that you are writing XHTML, that you need to add text alt:)

0
source

All Articles