tags:

views:

62

answers:

4

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="#">link</a></li>
        <li><a href="#">link</a></li>
        <li><a href="#">link</a></li>
    </ul>
</div>

What's the best way?

A: 

one line:

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

or two lines:

$('#gallery a').wrap('<li/>');
$('#gallery').wrapInner('<ul id="carousel"/>');
Moin Zaman
A: 
$('#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

Ninja Dude
+4  A: 

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().

patrick dw
I wonder if there is a performance difference between this method and Nicks?
Kamikaze Mercenary
@Kamikaze - I'd say this is a little more efficient because it doesn't require the `.parent()` traversal. The amount of wrapping taking place in both is identical.
patrick dw
@patrick - It depends, it'll be very, very close, but as always, test! http://jsperf.com/gallery-wrap-test
Nick Craver
@Nick - Surprising that the extra traversal is faster in some browsers. I tried to run tests in IE, but it gives me the slow running script warning. Any idea how to disable that?
patrick dw
+2  A: 

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).

Nick Craver