0

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.

Suzanne
  • 21
  • 5

1 Answers1

0
$('#postlist li').each(function() {
$('.comment').each(function() {
    var commentMeta = $(this).children('h4').detach();
    commentMeta.appendTo($(this))
});
});

DEMO

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();
  }
})
Udit Bhardwaj
  • 1,761
  • 1
  • 19
  • 29
  • That did it :) Thanks. If you have answers for either of the extras, let me know. Cheers. – Suzanne Nov 23 '13 at 14:14
  • @Suzanne - this doesn't do what you've asked for in your question, it appends the H4 into the `.commentcontent` element, and you expicitly asked for the H4 to "follow the DIV", not be inside it ? – adeneo Nov 23 '13 at 14:16
  • @Suzanne oops forgot that while editing. Changed `appendTo($(this).children('.commentcontent'))` to `appendTo($(this))` – Udit Bhardwaj Nov 23 '13 at 14:20
  • @adeneo You are correct. But that works as well so long as it followed the content and landed before the comment form that gets injected. – Suzanne Nov 23 '13 at 14:26