开发者

Wrap anchors in list tags in jQuery

开发者 https://www.devze.com 2023-01-18 22:53 出处:网络
I have some code like this: <div id=\"gallery\"> <a href=\"#\">link</a> <a href=\"#\">link</a>

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"/>');
0

精彩评论

暂无评论...
验证码 换一张
取 消