Convert Content inside div to UL li

北城余情 提交于 2019-12-11 10:09:45

问题


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


回答1:


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() { ... });



回答2:


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

  • http://jsfiddle.net/8DsZA/

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');


来源:https://stackoverflow.com/questions/21270413/convert-content-inside-div-to-ul-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!