Turbodurso
Turbodurso

Reputation: 61

How to wrap sibling elements?

The following markup will have some extra elements injected into it (i.e.: 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>

Upvotes: 0

Views: 2619

Answers (3)

Topher Fangio
Topher Fangio

Reputation: 20687

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);
});

Upvotes: 2

KyleFarris
KyleFarris

Reputation: 17557

$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);
});

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532765

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>');
});

Upvotes: 1

Related Questions