Search code examples
javascriptjquerywrapall

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


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.


Solution

  • 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");