colapsnux colapsnux - 5 months ago 18
HTML Question

Wrap each element in separate ul list

I have mutli

<a>
element wrapped into one div and I would like to wrap all the
<a>
tags into a
<ul>
list.

The html look like this :

<div id='MyId'>
<a href='#'><span>1</span></a>
<a href='#'><span>2</span></a>
<a href='#'><span>3</span></a>
<a href='#'><span>4</span></a>
<a href='#'><span>5</span></a>
</div>


And I would like to have

<div id='MyId'>
<ul>
<li>
<a href='#'><span>1</span></a>
</li>
<li>
<a href='#'><span>2</span></a>
</li>
<li>
<a href='#'><span>3</span></a>
</li>
<li>
<a href='#'><span>4</span></a>
</li>
<li>
<a href='#'><span>5</span></a>
</li>
</ul>
</div>


I tried with jquery but I'm not able to do it

$('#MyId').each(function(){
var $this = $(this),
html = $this.html(),
skel = '<ul><li>'+ html +'</li></ul>';

$this.closest('div').html('');

$('#MyId').append(skel);

});


Here some fiddle

Any help would be appreciated.

Answer

Use wrapAll() and wrap() methods

$('#MyId a')
  .wrapAll('<ul>') // wrap all elements by `ul`
  .wrap('<li>'); // wrap each element by `li`

console.log(
  $('#MyId').html()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='MyId'>
  <a href='#'><span>1</span></a>
  <a href='#'><span>2</span></a>
  <a href='#'><span>3</span></a>
  <a href='#'><span>4</span></a>
  <a href='#'><span>5</span></a>
</div>

Comments