While having one of my questions answered, cletus mentioned that when creating elements in jQuery it’s better to use direct DOM element creation, instead of innerHTML. I tried googling it but I wasn’t able to find a good article with comparisons.
I’ve provided this code bellow as an example and I was wondering if someone could help me rewrite it in direct DOM element creation form in hope that i would also learn the difference afterwards.
var img = $(this);
img.append('<p class="cap"><a href="'+img.parent().attr('href')+'">'+
img.attr('title')+'</p></a>');
Thanks so much.
Yeah, avoid HTML string-slinging. You’re giving yourself bugs and potentially cross-site scripting security holes. For example:
what if the URL in the parent’s
hrefcontains characters that are special in this HTML context, like<,"or&? At best you’ll get invalid markup that might trip the browser up; at worst, if the URL comes from user submission, a security problem.(OK,
<and"are unlikely to appear in a URL, but&is very likely indeed. Thetitleyou’re putting in the text content may be more vulnerable.)This is a large and increasing problem. Just as we’re starting to get a handle on fixing the HTML-injection bugs coming from templating on the server-side (eg. PHP users forgetting to
htmlspecialchars()), we’re now introducing loads of new client-side XSS from naïve HTML-hacking withinnerHTMLand jQuery’shtml(). Avoid.You can escape text you’re inserting into HTML manually:
but really, you’re better off using the direct DOM-style properties and methods, which, since they involve no HTML parsing, don’t require any escaping. They’re called DOM-style because that’s the way the original DOM Level 1 HTML features work (which existed back before
innerHTMLreared its ugly head):In jQuery you use
attr()andtext()to do the same:And in jQuery 1.4, you can do it most conveniently using an element creation shortcut:
This still looks a bit questionable though, what’s the parent that you’re getting the
hreffrom? It’s invalid to put a<p>, or another link, inside a link.