Reputation: 334
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!
Upvotes: 1
Views: 61
Reputation: 413727
$('.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
Upvotes: 1
Reputation: 8086
Try to limit by parent:
$(document).ready(function(){
$('.submittedby:parent').each(function(){
$(this).find('.submittedby').copy().appendTo('.threadtitle');
})
});
Upvotes: 0
Reputation: 1751
$('.submittedby').each(function() {
$(this).prev('.threadtitle').append($(this).html());
});
Upvotes: 1
Reputation: 125488
$(document).ready(function(){
$('span.submittedby, div.submittedby').each(function() {
self = $(this);
self.before(self.clone());
});
});
Upvotes: 0
Reputation: 630419
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.
Upvotes: 4