问题
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=&page=2">2</a>
<a href="/article/the-hub?i=&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