Wrap anchors in list tags in jQuery
I have some 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 using jQuery to produce:
<div id="gallery">
<ul id="carousel">
<li><a href="#">lin开发者_JS百科k</a></li>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
</ul>
</div>
What's the best way?
Example: http://jsfiddle.net/pB98T/
$('#gallery > a').wrapAll('<ul id="carousel">').wrap('<li>');
This wraps all the <a>
elements with the <ul id="carousel">
using .wrapAll()
, then wraps them individually with <li>
using .wrap()
.
This should do it:
$("#gallery a").wrap("<li />").parent().wrapAll("<ul id='carousel' />")
You can test it here (added some CSS to see the result clearer). Remember to call .parent()
after .wrap()
, since .wrap()
returns the original element (the <a>
, not the new <li>
parent).
$('#gallery a').each(function() {
$(this).wrap('<li class="liclass"/>');
});
$('.liclass').wrapAll('<ul class="ulclass"/>');
Refer : .wrap , .wrapAll
you can test its functionality http://jsbin.com/iluxe4
one line:
$('#gallery').wrapInner('<ul id="carousel"/>').find('a').wrap('<li/>');
or two lines:
$('#gallery a').wrap('<li/>');
$('#gallery').wrapInner('<ul id="carousel"/>');
精彩评论