Alex Rivera | Logout

jQuery .wrap() isn't working

Asked 2010-08-25T20:24:58.360
18

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

1 Answer

57

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.

answered 2012-09-21T03:30:08.737

Your Answer