I currently have a form that submits through ajax and when it’s successful it puts the information at the top of a list.
My current layout is
<div id="projects">
<div class="project">
....
</div>
<div class="project">
....
</div>
....
</div>
And I do the inserting by
var project = $('<div class="project">' +
'<div class="name">'+data.title+'</div>' +
'<div class="desc">'+data.desc+'</div>' +
'</div><hr />').fadeIn(1000, function() { }
);
$('.project:first-child').before(project);
$('.project:first-child').highlightFade({color:'#e3e373',speed:4000,iterator:'exponential'});
This works fine once there’s something in the list, but when there is nothing there it fails (because it can’t find a class with project.
How would I go about improving this so it’ll work even if there are no projects in the list?
I would do it slightly differently.
First, I would avoid constructing markup that way, at least in parts. If
data.titlecontains, say,<then it won’t be escaped properly. It’s better to usetext()for that.Second, it’s faster to create DOM elements rather than insert raw markup. In this case
$("<div>")is equivalent to$(document.createElement("div")).Third, use
prependToto insert the content. Then you have no issues.So: