How to add an element before the first element?
I am working on a comments system, using PHP + jQuery. I need to add the last comment to the top, before all the div
elements. E.G.
<div id="comment">
<div class="comment-3"></div>
<div class="comment-2"></div>
<div class="comment-1"></div>
</div>
So now I want to add the new <div class="comment-4"></div>
with jQuery to look like that:
<div id="comment">
<div class="comment-4"></div>
<div class="comment-3"></div>
<div class="comment-2"></div>
<div class="comment-1"></div>
</div>
Edit: NOTE: I am using:
$.ajax({
type: "POST", url: "ajax.php", cache : false, data: goData, dateType: "text",
success: function(data){
$("#comment").append(data);
$("#submit").attr({ disabled:false, value:"Shout开发者_如何学C it!" });
}
});
$("div#comment").prepend('<div class="comment-4"></div>');
Or more realistic
//something which generates a HTML DOM element
var newComment = ....;
$("div#comment").prepend(newComment);
Of course you can use the prependTo
syntax to if that is more natural for you
//something which generates a HTML DOM element
var newComment = ....;
$(newComment).prependTo("div#comment");
For more such tricks check the jQuery documentation
jQuery 1.3 Manipulation API
There are several ways, for example the prependTo method:
$('<div class="comment-4"></div>').prependTo('#comment');
jQuery: before
DOM: insertBefore
I think what you are really looking for is a selector for selecting the first comment, no matter what number of them you have (excuse if I am making a poor assumption) then giving it a class greater than the existing class with a name of comment-X where X is some number.
Thus:
$("#comment > div[class^=comment-]:first").before('<div class="comment-'+$('div[class^=comment-]').length)+1+'"></div>');
EDIT: OH, and the #comment > portion is to select the id of "comment" first, which makes it faster, but not strickly required unless you have more than one comment section such as somewhere else...
EDIT2: Added the .parent() selector - I typed too fast. EDIT3: need more coffee, changed .parent().prepend to .before
精彩评论