如何使用jQuery.wrapAll()包装多个元素?

要在jQuery中包装多个元素,请使用wrapAll()方法。wrapAll()方法将匹配集中的所有元素包装到单个包装器元素中。

这是此方法使用的所有参数的说明:

  • html- 将动态创建并包装在每个目标周围的HTML字符串。

示例

您可以尝试运行以下代码来学习如何使用jQuery.wrapAll()方法包装多个元素-

<html>

   <head>
      <title>jQuery wrap() method</title>
      <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               var content = "<div class = 'div'></div>";
               $("div").wrapAll( content );
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
       
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" id = "destination">THIS IS TEST</div>
      <div class = "div" style = "background-color:blue;">ONE</div>
      <div class = "div" style = "background-color:green;">TWO</div>
      <div class = "div" style = "background-color:red;">THREE</div>
       
   </body>
   
</html>