简体   繁体   中英

Convert Content inside div to UL li

I have some very old server side code that creates pagination links

<div class="pagination ">
    <span class="previous"></span>
    <span class="current">1</span>
    <a href="/article/the-hub?i=&amp;page=2">2</a>
    <a href="/article/the-hub?i=&amp;page=2" class="next">NEXT</a>
</div>

Is there an easy way with jquery to convert all the content within the div.pagination block to be ul li elements ?

Each a tag would nee to remain, and quite possibly the span tags also.

Any ideas greatly appreciated

This can be done with jquery, though it would be definitely more advisable to actually re-write the html.

However, if you want to do the conversion with jquery, whilst retaining all tags, the folllowing will work fine.

EXAMPLE


CODE

//select the original pagination div
var container = $('.pagination');

//prepare a new list container
var newContainer = $('<ul></ul>');

//iterate through all the children within the container and wrap them with a <li> tag
container.children().each(function(i) {
    var item = $(container.children()[i]).clone().wrapAll("<div/>").parent().html();
    newContainer.append('<li>'+item+'</li>');
});

//take out the old content
container.empty();
//add the new html structure
container.append(newContainer);

//give the old div a new class 
container.addClass('paginationContainer');

//swap out the pagination class to the new 'pagination' container
container.removeClass('pagination');
newContainer.addClass('pagination');

This should do the trick:

var $ul = $("<ul>");
$(".pagination").children().each(function()
{
    var $li = $("<li>").append($(this));
    $ul.append($li);
});
$(".pagination").append($ul);

jsFiddle : http://jsfiddle.net/hescano/5TZgb/

While we might intuitively think that we are re-creating the DOM elements, we are not. This code simply wraps the Div's children with li tags, and re-places the elements in the DOM.

If you want a more specific selector, you may try:

$(".pagination span, .pagination a").each(function() { ... });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM