jQuery AppendTo

576 views Asked by At

I'm not sure why this jQuery is outputting malformed HTML:

<img src="http://farm6.static.flickr.com/5300/5459333519_0bfb0763b0_m.jpg">

From this code:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=59597329@N08&lang=en-us&format=json&jsoncallback=?", function(data){
    $.each(data.items, function(i,item){
        $("<img>").attr("src", item.media.m).appendTo("#mac");
    });
});

#mac is the div to hold the images

Can anyone make sense of this?

2

There are 2 answers

1
T.J. Crowder On BEST ANSWER

That HTML is perfectly valid. (For XHTML you'd have to use a self-closing element.)

But that doesn't matter, because by the time jQuery is modifying things, it's interacting with the DOM (the markup part of things is pretty much over, except that jQuery uses innerHTML when it can under-the-covers). So you won't see the result as markup except in tools (like Firebug) that will show you DOM structures as HTML strings. If you're using an XHTML document, perhaps whatever tool you're using isn't following XHTML convention for display purposes, but that's just a display problem, not an actual problem with the page.

Think of it this way: Markup is like a string literal in your source code; the DOM is like the actual string at runtime. Debuggers will show you a string's contents at runtime, usually using similar notation to string literals (though that varies); similarly, tools like Firebug and Chrome's dev tools, etc., show you DOM structures using markup notation. But that's just a display thing in the tool.

4
jAndy On

It's not jQuerys .appendTo which causes the "problem". At snippet like this:

var bar = document.createElement('img');
    bar.setAttribute('src', 'http://farm6.static.flickr.com/5300/5459333519_0bfb0763b0_m.jpg');
    document.body.insertBefore(bar, document.body.firstChild);

will also create an <img> node without a closing </img>. Anyway this is absolutly fine and valid in all browsers. If some XHTML validation does complain about this, you may ignore it gracefully.