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.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

3 Answers3

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");
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • @Matthew, `wrapAll()` returns the wrapped element. See [this fiddle](http://jsfiddle.net/2e2WL/), it will say `DIV` and not `P`. – Frédéric Hamidi Aug 07 '11 at 12:39
  • 1
    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. `
    `), then parent will not get the outermost wrapper, as is most likely expected.
    – jbyrd Nov 19 '18 at 18:46
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.

karim79
  • 339,989
  • 67
  • 413
  • 406
-2
$(function() {
    var wrapper = $("<div class='wrapper'></div>");
    var wrapped = $(".a").wrapAll(wrapper);
    wrapped.css("border", "5px solid black");
});
Billy Moon
  • 57,113
  • 24
  • 136
  • 237