Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap particular multiple divs with jQuery

Just trying to work with jQuery wrapInner and I could not wrap particular multiple divs with a outer div.

$('#outer').not('#inner3')
  .wrapInner('<div id="wrapper" style="background:green;"></div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='outer'>
  <div id='inner1'>1</div>
  <div id='inner2'>2</div>
  <div id='inner3'>3</div>
</div>

How to wrap inner1 and inner2 within another div. I tried like above but this wraps whole 3 inner divs.

Output required:

<div id='outer'>
  <div id="wrapper" style="background:green;">
    <div id='inner1'>1</div>
    <div id='inner2'>2</div>
  </div>
  <div id='inner3'>3</div>
</div>
like image 808
hsuk Avatar asked Dec 05 '13 07:12

hsuk


2 Answers

Try $('#outer div').not('#inner3')

$(document).ready(function () {
    $('#outer div').not('#inner3')
        .wrapInner('<div id="hey" style="background:green;"></div>');
});

fiddle Demo


$('#outer div').not('#inner3') select all div inside element with id outer but not with element with id inner3
if you want two put first two children you can use :lt()

fiddle Demo

$(document).ready(function () {
    $('#outer div:lt(2)')
        .wrapInner('<div id="hey" style="background:green;"></div>');
});


Update after OP's comment

Updated fiddle Demo

$(document).ready(function () {
    $('#outer div').not('#inner3')
        .wrapAll('<div id="hey" style="background:green;"></div>');
});
like image 139
Tushar Gupta - curioustushar Avatar answered Sep 28 '22 18:09

Tushar Gupta - curioustushar


Use the .wrapAll() function:

$('document').ready(function() {
  $('#outer div').not('#inner3')
    .wrapAll('<div id="hey" style="background:green;"></div>');
});

Check this link for more info.

From the documentation:

Description: Wrap an HTML structure around all elements in the set of matched elements.

.wrapAll( wrappingElement )

wrappingElement

Type: Selector or htmlString or Element or jQuery

A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements.

.wrapAll( function )

function

Type: Function( Integer index ) => String or jQuery

A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the se

like image 25
NavaStha Avatar answered Sep 28 '22 19:09

NavaStha