link link link

Wrap anchors in list tags in jQuery

I have a code like this:

<div id="gallery"> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> </div> 

and I want to rewrite it with jQuery to create:

 <div id="gallery"> <ul id="carousel"> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> </ul> </div> 

What is the best way?

+4
source share
4 answers

Example: http://jsfiddle.net/pB98T/

 $('#gallery > a').wrapAll('<ul id="carousel">').wrap('<li>'); 

This wraps all the <a> elements with <ul id="carousel"> with .wrapAll() , then wraps them individually with <li> with .wrap() .

+4
source

This should do it:

 $("#gallery a").wrap("<li />").parent().wrapAll("<ul id='carousel' />")​ 

You can test it here (added CSS to see the result more clear). Remember to call .parent() after .wrap() , since .wrap() returns the original element ( <a> , not the new parent <li> ).

+2
source

one line:

 $('#gallery').wrapInner('<ul id="carousel"/>').find('a').wrap('<li/>'); 

or two lines:

 $('#gallery a').wrap('<li/>'); $('#gallery').wrapInner('<ul id="carousel"/>'); 
0
source
 $('#gallery a').each(function() { $(this).wrap('<li class="liclass"/>'); }); $('.liclass').wrapAll('<ul class="ulclass"/>'); 

Please note:. wrap , .wrapAll

you can check its functionality http://jsbin.com/iluxe4

0
source

All Articles