views:

41

answers:

5

In the HTML below, I would like to copy the "submittedby" beside "message", within the H2 tag:

<div class="comment">
<H2 class="threadtitle">Message 1</h2>
<span class="submittedby">James</a>
</div>

<div class="comment">
<H2 class="threadtitle">Message 2</h2>
<span class="submittedby">Bill</a>
</div>

<div class="comment">
<H2 class="threadtitle">Message 3</h2>
<div class="submittedby">Phil</a>
</div>

My current jQuery code is as follows:

$(document).ready(function() { 
    $('.submittedby').copy().appendTo('.threadtitle');
});

The problem is this copies EVERY "submittedby" to EVERY "threadtitle". How do I code it so it only copies the "submittedby" from within the same "comment" div? Thanks!

+1  A: 
$('.submittedBy'.each(function() {
  var $sb = $(this);
  $sb.copy().appendTo($sb.closest('.comment').find('h2.threadtitle'));
});

When you use .each() you get to have code run for each element processed.

edit thanks @Nick

Pointy
`.submittedBy` isn't a child of `.threadtitle` ;)
Nick Craver
Oh you'[re right; sorry, I misread it. (I guess it'd make no sense if it already were a child!)
Pointy
+4  A: 

Use .each() here, like this:

$(function(){ 
  $('.submittedby').each(function() {
    $(this).clone().appendTo($(this).siblings('.threadtitle'));
  });
});

This loops over each .submittedby element, and moved it around with respect to the current .submittedby you're on in the loop, so each one's handled individually. Also I assumed you meant .clone() here, but if you're actually using the .copy() plugin, just replace .clone() with .copy() in the code above.

Nick Craver
This did it - Thank you very much!
HipHop-opatamus
A: 
$(document).ready(function(){ 
    $('span.submittedby, div.submittedby').each(function() { 
        self = $(this);
        self.before(self.clone());
    });
});

Obligatory example

Russ Cam
+1  A: 
$('.submittedby').each(function() {
    $(this).prev('.threadtitle').append($(this).html());
});
Puaka
A: 

Try to limit by parent:

$(document).ready(function(){ 
    $('.submittedby:parent').each(function(){
        $(this).find('.submittedby').copy().appendTo('.threadtitle');
    })
});
Jage