Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap an existing element with another one in jQuery?

Tags:

html

jquery

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?

like image 852
newbie Avatar asked Dec 05 '11 01:12

newbie


People also ask

Which jQuery method allows you to add a wrapper element around another set of elements?

The wrap() method wraps specified HTML element(s) around each selected element.

What is wrap method in jQuery?

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))

What is slice () method in jQuery?

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.

How do you wrap two divs?

You can use wrapAll() function!


1 Answers

Use the .wrapAll() doc method

$('#test, #test2').wrapAll('<div class="test3">');
like image 124
Gabriele Petrioli Avatar answered Oct 07 '22 16:10

Gabriele Petrioli