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.
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>
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/
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With