views:

289

answers:

3

The following markup will have some extra elements injected into it (ie: a div containing some flash for example). How can i dynamically wrap all of the p tags in one div and add a button above it to toggle that newly made div?

<div class="post">
  <p>blquehrgéoqihrteoijth</p>
</div>

<div class="post">
  <p>blquehrgéoqihrteoijth</p>
  <p>blquehrgéoqihrteoijth</p>
  <p>blquehrgéoqihrteoijth</p>
  <p>blquehrgéoqihrteoijth</p>
</div>
+1  A: 

I would do the following for simplicity:

$('.post').prepend("<h3 class='showText'>biography</h3>\n<div class='toggle'>");
$('.post').append("</div>");

Should do what you require.

Edit 1: Added cballou's comment code here for easier readability:

$j('h3').live('click', function() {
  $j(this).toggleClass('hideText').slideToggle(300);
});
Topher Fangio
I concur with Topher. You would also want to utilize the jQuery "live" function to allow for the slideToggle event like so:$j('h3').live('click', function() { $j(this).toggleClass('hideText').slideToggle(300); });
cballou
Its obvioulsly a much more simple solution. But the markup itself will be injected by loads of other divs at times and I only want the toggle the p tags. Unfortunately I have no access server-side to change the markup there ...
Turbodurso
+1  A: 

I'd just extract the existing HTML and wrap it (as text), then reinsert it.

$('.post').each( function() {
    $(this).html('<h3 class="showText">biogrpahy</h3><div class="toggle">'
                  + $(this).html()
                  + '</div>');
});
tvanfosson
Yeah, that'll work quite well too.
KyleFarris
A: 
$j('.post').wrapAll("<div class='toggle'></div>");
$j('.toggle').before('<h3 class="showText">bibliography</h3>');
$j('h3').live('click',function(){
    $j(this).toggleClass('hideText');
    $j('.toggle').slideToggle(300);
});
KyleFarris