How to get the wrapper element created with "wrapAll()"?
Asked Answered
M

3

25

Consider the following code: (live example here)

$(function() {
  var wrapper = $("<div class='wrapper'></div>");
  $(".a").wrapAll(wrapper);
  wrapper.css("border", "5px solid black"); // Doesn't work
});
.wrapper {
  background-color: #777;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a">Hello</div>
<div class="a">Stack</div>
<div class="a">Overflow</div>

What would be the right way to get the created wrapper and change its attributes ?

Note: There are other .wrapper elements in the DOM, so this won't work:

$(".wrapper").css("border", "5px solid black");

I don't want to give a unique id to the created wrapper either.

Mccarver answered 7/8, 2011 at 12:32 Comment(0)
G
34

Since you just wrapped the elements, you can use parent() to obtain the newly inserted wrappers:

$(".a").wrapAll("<div class='wrapper'></div>")
       .parent().css("border", "5px solid black");
Glucoside answered 7/8, 2011 at 12:36 Comment(2)
@Matthew, wrapAll() returns the wrapped element. See this fiddle, it will say DIV and not P.Trinitytrinket
It would be nice to have a way to more robustly capture the resulting wrapper...using parent only goes one level up, but if someone came in and added a nested div as a wrapper (e.g. <div class="wrapper-outer"><div class="wrapper-inner"></div></div>), then parent will not get the outermost wrapper, as is most likely expected.Birthday
N
6

The jQuery object stored in wrapper gets cloned when wrapAll gets called, so you cannot affect the .wrappers which have been inserted into the DOM by manipulating wrapper, you need to select them from the document.

Norty answered 7/8, 2011 at 12:44 Comment(3)
+1 for explaining how wrapAll() works, though it doesn't answer my question.Mccarver
@Misha - I thought Frederic had already done that, just wanted to add a point.Norty
@Norty probably better to do that as a comment to the original answerCavefish
S
-2
$(function() {
    var wrapper = $("<div class='wrapper'></div>");
    var wrapped = $(".a").wrapAll(wrapper);
    wrapped.css("border", "5px solid black");
});
Skirting answered 7/8, 2011 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.