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.
Wrap a set of elements Select the element or elements that you want to enclose in a div. Use one of the following methods to wrap the selected elements: Select Edit > Wrap from the top menu.
jQuery wrap() Method The wrap() method wraps specified HTML element(s) around each selected element.
use Jquery . wrapAll() - It wraps the html structure around all the matched elements.
A wrapper div in an HTML document does the same things but to a layout instead of to actual property. The wrapper holds a design within certain boundaries. The various areas of a design cannot escape from the boundaries set by the wrapper.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With