Cloning a selector + all of its children in jQuery?
I'm having trouble getting the following JQuery script to work properly - its functionality is as follows:
1) Hide content under each heading
2) When clicking on the title, replace "# first-post" with title + hidden content below the title.
It seems I can get the script to clone the heading to # first-post, not the heading + content below it. Any idea why?
<HTML>
<HEAD>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</HEAD>
<script>
$(document).ready(
function(){
$('.title').siblings().hide();
$('.title').click( function() {
$('#first-post').replaceWith($(this).closest(".comment").clone().attr('id','first-post'));
$('html, body').animate({scrollTop:0}, 'fast');
return false;
});
});
</script>
<BODY>
<div id="first-post">
<div class="content"><p>This is a test discussion topic</p> </div>
</div>
<div class="comment">
<h2 class="title"><a href="#1">1st Post</a></h2>
<div class="content">
<p>this is 1st reply to the original post</p>
</div>
<div class="test">1st post second line</div>
</div>
<div class="comment">
<h2 class="title"><a href="#2">2nd Post</a></h2>
<div class="content">
<p>this is 2nd reply to the original post</p>
</div>
<div class="test">2nd post second line</div>
</div>
</div>
<div class="comment">
<h2 class="title"><a href="#3">3rd Post</a></h2>
<div class="content">
<p>this is 3rd reply to the original post</p>
</div>
<div class="test">3rd post second line</div>
</div>
</div>
</BODY>
</HTML>
+2
a source to share
2 answers
You also need to show hidden items. Note that replaceWith returns the removed element, so you need to query for the new "first-post" element and then the hidden descendants when displaying.
$('.title').click( function() {
$('#first-post').replaceWith($(this).closest(".comment").clone().attr('id','first-post'));
$('#first-post').find(':hidden')
.show();
$('html, body').animate({scrollTop:0}, 'fast');
return false;
});
+1
a source to share