views:

41

answers:

1

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?

+2  A: 

I would do it slightly differently.

First, I would avoid constructing markup that way, at least in parts. If data.title contains, say, < then it won't be escaped properly. It's better to use text() 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 prependTo to insert the content. Then you have no issues.

So:

$("<div>").addClass("project")
  .appendChild($("<div>").addClass("name").text(data.title))
  .appendChild($("<div>").addClass("desc").text(data.desc));
  .hide().prependTo("#projects").fadeIn(1000);
cletus
Thanks so much, this is my first time using Jquery so I'm still learning the API.
silent1mezzo
@silent no worries :)
cletus