How can I create a <div>
surrounding an existing <div>
.
My code is as follows:
<div id="test">
<h2>Greetings</h2>
<p>Test</p>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
</div>
<div id="test2">
<h2>Greetings</h2>
<p>Test</p>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
</div>
<script>
$("#test").before('<div class="test3">');
$("#test2").after('</div>');
</script>
But it seems that it cannot insert a <div>
without an end tag. So how to achieve that?
The wrap() method wraps specified HTML element(s) around each selected element.
jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector). wrap(wrappingElement,function(index))
slice() method constructs a new jQuery object containing a subset of the elements specified by the start and, optionally, end argument. The supplied start index identifies the position of one of the elements in the set; if end is omitted, all elements after this one will be included in the result.
You can use wrapAll() function!
Use the .wrapAll()
doc method
$('#test, #test2').wrapAll('<div class="test3">');
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