user2596635
user2596635

Reputation: 381

How can I wrap multiple elements that appear on the page multiple times with divs?

I have a form being generated through a CMS and I need to wrap the inputs and their labels to contain them within divs. Here's the HTML I have now:

<p><strong>Heading One</strong></p>
<p>Title One</p>
<input type="text" size="25" name="Title1" value="">
<br/>
<p>Title Two</p>
<input type="text" size="25" name="Title2" value="">
<br/>
<p>Title Three</p>
<input type="text" size="25" name="Title3" value="">
<br/>
<p>Title Four</p>
<input type="text" size="25" name="Title4" value="">
<br/>

This is what I'm hoping to achieve:

<p><strong>Heading One</strong></p>
<div class="wrapper">
     <p>Title One</p>
     <input type="text" size="25" name="Title1" value="">
</div>
<br/>
<div class="wrapper">
     <p>Title Two</p>
     <input type="text" size="25" name="Title2" value="">
</div>
<br/>
<div class="wrapper">
     <p>Title Three</p>
     <input type="text" size="25" name="Title3" value="">
</div>
<br/>
<div class="wrapper">
     <p>Title Four</p>
     <input type="text" size="25" name="Title4" value="">
</div>
<br/>

I tried this code here to achieve this:

$('form > p').each(function(){
    $(this).next('input[type="text"]').andSelf().wrapAll('<div class="wrapper"/>');
});

But it didn't work because it also wrapped the Heading p with the wrapper. Is there a way to achieve what I'm trying to do?

Upvotes: 1

Views: 100

Answers (2)

PeterKA
PeterKA

Reputation: 24638

$(function() {
    $('input').each(function() { 
        $(this).prev().addBack()
        .wrapAll( $('<div/>',{class:'wrapper'}) );
    });
});

$(function() {
    $('input').each(function() { 
        $(this).prev().addBack()
        .wrapAll( $('<div/>',{class:'wrapper'}) );
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p><strong>Heading One</strong></p>
<p>Title One</p>
<input type="text" size="25" name="Title1" value="">
<br/>
<p>Title Two</p>
<input type="text" size="25" name="Title2" value="">
<br/>
<p>Title Three</p>
<input type="text" size="25" name="Title3" value="">
<br/>
<p>Title Four</p>
<input type="text" size="25" name="Title4" value="">
<br/>

Upvotes: 1

kapantzak
kapantzak

Reputation: 11750

$('p').not(':first-of-type').each(function() {
    var that = $(this);
    var div = '<div class="wrapper"></div>';
    that.next().addBack().wrap(div);
});

Upvotes: 1

Related Questions