jQuery wrapAll()方法 用于给所有选定的元素的外部包裹一组元素。

它和jQuery wrap() 方法 的区别在于,jQuery wrap() 方法 是给每一个选定的元素都包裹,而jQuery wrapAll() 方法 是在外面只包裹一次。

语法

$(selector).wrapAll(wrappingElement) 

参数

参数说明
wrappingElement为必填参数。它指定您环绕所选元素的 HTML 元素。它的可能值是:HTML 元素jQuery 对象DOM 元素

例子

例1

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").wrapAll("<div></div>");
    });
});
</script>
<style>
div{background-color: pink;}
</style>
</head>
<body>
<p>jQuery wrapAll() 方法 </p>
<p> yxjc123.com</p>
<button>点击查看效果</button>
</body>
</html>
例2

<!DOCTYPE html>
<html>
<head>
<title>jQuery wrapAll()方法例子</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript" language="javascript">
         $(document).ready(function() {
            $("div").click(function () {
               var content = "<div class='div'></div>";
               $("div").wrapAll( content );
            });
         });
      </script>
<style>
.div{ margin:5px;padding:2px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
<p>点击任意方块将方块包裹成一个新方块:</p>
<div class="div" id="destination">我们要包装这个文本</div>
<div class="div" style="background-color:orange;">1</div>
<div class="div" style="background-color:yellow;">2</div>
<div class="div" style="background-color:green;">3</div>
</body>
</html>