[ How do I iterate over a nested UL to move an h4 from above a div to below it? ]
I have a blog theme that produces the following output for its blog index page. For each post (10 per page), it also iterates over the associated list of comments (n per post). Within each comment, there is an h4 element that precedes div.commentcontent.
<ul id="postlist">
<li class="post">
<h2>Post Title</h2>
<p>Here is some post content</p>
<ul class="commentlist">
<li class="comment">
<h4>Comment Author Name <span class="meta">Date</span></h4>
<div class="commentcontent">Here is the comment text</div>
</li>
</ul>
</li>
</ul>
On page load, I need to reposition the h4 in each comment so that it follows the div.
I've read up on detach and appendTo and I attempted to use this snippet to iterate over each post and then each comment within the post, but this is not working.
$('#postlist li').each(function() {
$('.comment').each(function() {
var commentMeta = $('.comment').children('h4').detach();
commentMeta.appendTo('.comment').children('.commentcontent');
});
});
Extra: I also have AJAX handling comment posting so as new comments are posted, they need to have the h4 repositioned as well, even tho the page has not refreshed.
Extra 2: Is it possible to wrap span tags around the comment author name?
Any help would be much appreciated. Thanks.
Answer 1
$('#postlist li').each(function() {
$('.comment').each(function() {
var commentMeta = $(this).children('h4').detach();
commentMeta.appendTo($(this))
});
});
EDIT:- for ajax comment posting you can create a function and call that on success/done of the ajax method
function swap()
{
$('#postlist li').each(function() {
$('.comment').each(function() {
if($(this).children(':first-child').prop('tagName')=="H4")
{
var commentMeta = $(this).children('h4').detach();
commentMeta.appendTo($(this))
}
});
});
}
$.ajax(
{
url: //,
data: //,
success: function()
{
swap();
}
})