且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将div内的内容转换为UL li

更新时间:2022-10-21 10:15:14

这应该会有诀窍:

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

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

虽然我们可能会直觉地认为我们正在重新创建DOM元素,我们不是。此代码只是用 li 标签包装Div的子元素,并将元素重新放置在DOM中。



如果你想要一个更具体的选择器,你可以尝试:

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


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