0

I have some elements like

<div id="one">ONE</div>
<div id="two">TWO</div>
<div id="three">THREE</div>
<div id="four">FOUR</div>
<div id="five">FIVE</div>

Now I want to wrap a DIV tag around the two elements with the ID "two" and "three" to get this:

<div id="one">ONE</div>
<div class="wrapped">
    <div id="two">TWO</div>
    <div id="three">THREE</div>
</div>
<div id="four">FOUR</div>
<div id="five">FIVE</div>

With the "wrapAll" function i can only target elements with the same class I think like:

$(document).ready(function(){
    $( "div" ).wrapAll( "<div class='wrapped' />");
});

I know I could give the two DIVs the same class with jquery first and then wrap them but I hope there is a more elegant way.

herrfischer
  • 1,768
  • 2
  • 22
  • 35
  • 2
    `I want to wrap a DIV tag around the two elements with the ID "two" and "four"` Did you mean `two` and `three`? That's what your example would suggest. If so, use `$('#two, #three').wrapAll(...` – Rory McCrossan Jan 07 '16 at 16:09
  • 1
    Possible duplicate of [jQuery - use wrap() to wrap multiple elements?](http://stackoverflow.com/questions/3475594/jquery-use-wrap-to-wrap-multiple-elements) – random_user_name Jan 07 '16 at 16:10
  • 2
    Just use `$("#two, #three").wrapAll( "
    ");` -- Example [here](https://jsfiddle.net/kgxpjhfu/)...
    – Josh Crozier Jan 07 '16 at 16:11
  • You just need to select DIVs two and three: `$("#two, #three).wrapAll...` If it's more difficult than this, you'll need add more information. – Tony Hinkle Jan 07 '16 at 16:11

2 Answers2

5

You can do it with $('#two, #three').wrapAll('<div class="wrapped" />')

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
2

Just select the the two you want and wrapAll().

From docs (emphasis my own):

The .wrapAll() function can take any string or object that could be passed to the $() function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around all of the elements in the set of matched elements, as a single group.

Fiddle: https://jsfiddle.net/93dyokr0/1/

$('#two, #three').wrapAll( "<div class='wrapped' />");
AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43