Josh Scott
Josh Scott

Reputation: 3840

Using jQuery: Wrapping div in another div with .before()

I am trying to use jQuery to add a div around the following code:

<div class="fsSubField">
<input id="field15744501-zip" class="fsField fsFieldZip fsFormatZipCA" type="text" value="" size="8" name="field15744501-zip">
<br>
<label class="fsSupporting" for="field15744501-zip">Postal Code</label>
</div>

So that in the end I have:

<div class="fsSubFieldGroup" style="margin-top:5px;">
<div class="fsSubField">
<input id="field15744501-zip" class="fsField fsFieldZip fsFormatZipCA" type="text" value="" size="8" name="field15744501-zip">
<br>
<label class="fsSupporting" for="field15744501-zip">Postal Code</label>
</div>
</div>

I tried the following:

$('input.fsFormatZipCA').parent().before('<div> class="fsSubFieldGroup" style="margin-top:5px;">');
$('input.fsFormatZipCA').parent().after('</div>');

Because of the dynamic nature of the form I need to be able to base the select on 'input.fsFormatZipCA'

I would think this would work but the problem is that jQuery is doing the following:

<div class="fsSubFieldGroup" style="margin-top: 5px;"></div>
<div class="fsSubField">
<input id="field15744501-zip" class="fsField fsFieldZip fsFormatZipCA" type="text" value="" size="8" name="field15744501-zip">
<br>
<label class="fsSupporting" for="field15744501-zip">Postal Code</label>
</div>

Upvotes: 2

Views: 235

Answers (3)

David Thomas
David Thomas

Reputation: 253338

I'd suggest:

$('.fsFormatZipCA').parent().wrap('<div class="fsSUbFieldGroup" />');

Upvotes: 1

Hidde
Hidde

Reputation: 11941

Use .wrap():

$('input.fsFormatZipCA').parent().wrap('<div class="fsSubFieldGroup" style="margin-top:5px;">');

More info in the jQuery docs: http://api.jquery.com/wrap/


Sidenote: You maybe notice that the .wrap() function adds hte </div> for you. It makes stuff a lot easier.

Upvotes: 2

pimvdb
pimvdb

Reputation: 154868

You seem to be looking for .wrap:

$('input.fsFormatZipCA').parent().wrap(
  $('<div>', {
    'class': 'fsSubFieldGroup',  // class is a reserved word
    css: {
      'margin-top': 5  // - is an invalid identifier character
    }
  })
);

.before inserts an element before an element. It does not construct the HTML by plainly prepending an HTML string.

Upvotes: 3

Related Questions