-3

Is there some analogue of wrapAll() in jQuery just for JavaScript? I need to wrap all list elements inside UL except the first one in DIV, is there any way? Can you please tell me...

Suraj Rao
  • 28,850
  • 10
  • 94
  • 99
  • Can you provide example input/output, and explain what is holding you back from doing it? NB: jQuery is JavaScript. – trincot May 19 '22 at 06:07
  • I don't think that would be valid HTML. A `div` can't be a child of a `ul` element. – Andy May 19 '22 at 06:19
  • Also: https://stackoverflow.com/questions/6838104/pure-javascript-method-to-wrap-content-in-a-div – Andy May 19 '22 at 06:20

1 Answers1

0

This is a function that will create a new div element containing the unordered list passed to it. The demo just clones a ul element already existing in the document and appends it to #target after wrapping its content (except the first list item) in a new div.

const ul = document.querySelector('#list').cloneNode(true);
const newContainer = wrapAll(ul);

document.querySelector('#target').appendChild(newContainer);

function wrapAll(ul){
  const wrapper = document.createElement('div');
  ul.removeChild( ul.children[0] );
  wrapper.appendChild(ul);
  return wrapper;
}
<h1>Source List</h1>

<ul id="list">
  <li id="a">First Item</li>
  <li>Second Item</li>
  <li>Third Item</li>
</ul>

<h1>Cloned List</h1>

<div id="target">
</div>
Diego De Vita
  • 2,262
  • 1
  • 14
  • 23