CoryDorning
CoryDorning

Reputation: 1914

jQuery .wrap() isn't working

I'm probably doing something wrong but I've tried all sorts of things and can't seem to get a collection of jQuery objects wrapped. The following just outputs the link HTML, unwrapped. Any ideas?

$.each(sitemapSections, function(i) {
  var $sitemapSection = $(sitemapSections[i]);
  var $primary = $sitemapSection.find('a[data-level="1"]').wrap('<h3></h3>');

  $dropdownSections[i].html($primary);
});

EDIT - here's the markup (cleaned up):

<li id="product-solutions"><a href="#link" class="alpha grid-6">Products &amp; Solutions</a>

  <div id="ps-dropdown" class="dropdown-menu grid-20">
    <div class="ps-dropdown-section">

    </div><!-- .ps-dropdown-section -->

    <div class="ps-dropdown-section">

    </div><!-- .ps-dropdown-section -->

    <div class="ps-dropdown-section">

    </div><!-- .ps-dropdown-section -->
  </div><!-- .dropdown-menu -->
</li>

UPDATE - I got it! The comments who mentioned parent() is what I was missing. Here's the final code:

$.each(sitemapSections, function(i) {
  var $sitemapSection = $(sitemapSections[i]);
  var $primary = $sitemapSection.find('a[data-level="1"]').wrap('<h3></h3>').parent();

  $dropdownSections[i].html($primary);
});

Upvotes: 18

Views: 13779

Answers (3)

fastmultiplication
fastmultiplication

Reputation: 3081

jquery .wrap() returns the INNER element back to you, so it looks like nothing changed.

$("<div>").wrap('<span>') 

===> 

[<div></div>]

which looks like it didn't work.

but:

$("<div>").wrap('<span>').parent()

===>

[<span><div></div></span>]

it actually did work.

Upvotes: 56

Andrew Wirick
Andrew Wirick

Reputation: 184

It looks like you mean to use jQuery's html method to add html in the second to last line - unless $dropdownSections is an array with each element being a jQuery object. I think you might be after this:

$.each(sitemapSections, function(i) {
  var $sitemapSection = $(sitemapSections[i]);
  var $primary = $sitemapSection.find('[data-level="1"]').wrap('<h3></h3>');

  $dropdownSections.eq(i).html($primary.parent().html());
});

or more written another way:

$.each(sitemapSections, function(i) {
  $dropdownSections.eq(i).html(
    $(sitemapSections[i])
    .find('[data-level="1"]')
    .wrap('<h3></h3>')
    .parent()
    .html()
  );
});

if $dropdownSections is an array which has a jQuery object in each element:

$.each(sitemapSections, function(i) {
  $dropdownSections[i].html(
    $(sitemapSections[i])
    .find('[data-level="1"]')
    .wrap('<h3></h3>')
    .parent()
    .html()
  );
});

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630429

You need a string to pass into .html(), I think you're after this instead:

 $dropdownSections[i].empty().append($primary.parent());

This gets the .parent() (since you just wrapped it in one) and sets the contents to that.

Upvotes: 0

Related Questions