[英]jQuery wrap element around a lot of elements
我有跟随html并希望用javascript或jquery包装所有li的div(它没有定义有多少li)
<div class='example1'>
<div class='example2'>
<h1>Test</h1>
<div class='example3'>
<li></li>
<li></li>
...
<li></li>
<li></li>
</div>
结果应该是这样的
<div class='example1'>
<div class='example2'>
<h1>Test</h1>
<div class='example3'>
<div class='lis'>
<li></li>
<li></li>
...
<li></li>
<li></li>
</div>
</div>
我无法添加任何其他现有的html :(
你能帮我么?
用这个 :
(function($) {
$.fn.customWrap = function(wrapper) {
if (!this.length) return this;
var wrap = $(wrapper),
sel = this.selector || this.get(0).nodeName.toLowerCase();
return this.each(function() {
var more = $(this).next(sel).length;
console.log(this,more);
$(this).replaceWith(wrap).appendTo(wrap);
if (!more) wrap = $(wrapper);
});
}
})(jQuery);
并调用如:
$(function() {
$('li').customWrap('<div class="lis"></div>');
});
或者您可以使用jQuery wrapAll但这将包装页面中的所有li
..而不是连续的..
你可以使用$ .wrap()将匹配元素集包装在另一个元素中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.