解包div包装器,然后换入无序列表并将子包装在列表项中

时间:2014-01-05 02:02:24

标签: jquery html-lists

我有以下标记:

 <div class="idx-results idx-grid grid_size_2 clearfix">
  <div class="row">
    <div class="col grid_6_of_12 featlist">a</div>
    <div class="col grid_6_of_12 featlist">b</div>
 </div>

我想实现以下输出:

 <div class="idx-results idx-grid grid_size_2 clearfix">
  <ul class="bxslider">
    <li class="col grid_6_of_12 featlist">a</li>
    <li class="col grid_6_of_12 featlist">b</li>
 </ul>

我认为这将是解决方案,但没有骰子!

$(".idx-results .row").unwrap().wrap('<ul/>');

2 个答案:

答案 0 :(得分:2)

您只需unwrap() contents()并使用新元素重新wrap()

但是如果你想保留旧元素的所有attributes,那么这应该是解决方案:

var $old = $('.row'),
    $new = $('<ul/>');
//loop through all the attributes of the $old element
//then set it on our new element - $new
$.each($old[0].attributes, function (i, attr) {
    $new.attr(attr.name, attr.value);
});
//copy the $old element html contents
$new.html($old.html());
//and swap with the $new element
$old.replaceWith($new);

请参阅此jsfiddle demo

答案 1 :(得分:1)

尝试

$('.idx-results > .row').wrapInner('<ul />').contents().unwrap();
$('.idx-results .col').wrapInner('<li />').contents().unwrap()

演示:Fiddle