如何在jQuery中将现有元素与另一个元素包装在一起?

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

示例

您可以尝试运行以下代码,以了解如何在jQuery中将现有元素与另一个元素包装在一起:

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
 
     $("#button3").click(function(){
        $('#demo, #demo2').wrapAll('<div class="demo3">');
    });
   
});
</script>
<style>
  div {
    background-color: green;
  }
</style>
</head>
<body>

<div id="demo">
  <h2>Heading 2</h2>
  <p>This is demo text.</p>
  <p>Test</p>
 
</div>
<div id="demo2">
  <h2>Heading 2</h2>
  <p>This is demo text.</p>
  <p>Test</p>
</div>

<button id="button3">Wrap all</button>

</body>
</html>