Claire
Claire

Reputation: 3773

How to add whole section to a bunch of html elements using jquery?

I want to add a section of class="box" to the contents of the div id="primary", excluding the h1. My html is below.

<div id="primary">

    <h1 class="page-title">Search Results for: dffd</h1>        

        <h2>Nothing Found</h2>
        <p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>


 </div> <!--end #primary -->

So what I want to achieve is

<div id="primary">

  <h1 class="page-title">Search Results for: dffd</h1>  

 <section class="box">



        <h2>Nothing Found</h2>
        <p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>

   </section>

 </div> <!--end #primary -->

EDIT: made a mistake, I don't want my h1 in the section, have amended question

Upvotes: 1

Views: 92

Answers (2)

adeneo
adeneo

Reputation: 318222

$('#primary').children().not('h1').wrapAll('<section class="box"></section>');

Upvotes: 2

Madbreaks
Madbreaks

Reputation: 19539

Use jQuery's wrapInner:

$('#primary').wrapInner('<section class="box" />');

--EDIT--

Saw your revised question, try this:

// Wrap the contents in with the section
$('#primary').wrapInner('<section class="box" />');

// Detach (remove, but retain events/data) the <h1>, then prepend it to the primary div
$('#primay .box h1').detach().prependTo('#primary');

There are many ways you could do this, of course.

Cheers

Upvotes: 4

Related Questions