Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap each element in separate ul list

Tags:

html

jquery

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.

like image 976
colapsnux Avatar asked Jun 05 '16 11:06

colapsnux


3 Answers

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>
like image 62
Pranav C Balan Avatar answered Nov 02 '22 23:11

Pranav C Balan


Try using wrap() and wrapInner() link: http://api.jquery.com/wrap/

$('#MyId > a').wrap('<li></li>');
// Wrap all a tag with <li></li>
$('#MyId').wrapInner('<ul></ul>');
<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>

fiddle: https://jsfiddle.net/5zh77tep/3/

like image 31
weigreen Avatar answered Nov 02 '22 23:11

weigreen


You can use wrapInner() to wrap content of #MyId div in ul and then use wrap() to wrap each a in li

$('#MyId').wrapInner('<ul>')
$('#MyId a').wrap('<li>');
li { display:block; list-style:none }
li > a { display:block; margin:.5em 0 }
<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>
like image 21
Nenad Vracar Avatar answered Nov 02 '22 22:11

Nenad Vracar