.wrapAll()

.wrapAll( wrappingElement ) 官网原E文:jQuery

Description: 在所有匹配元素外面包一层HTML结构。

  • version added: 1.2.wrapAll( wrappingElement )

    wrappingElement用来包在外面的HTML片段,选择表达式,jQuery对象或者DOM元素。

参数可以是string或者对象,只要能形成DOM结构,可以是嵌套的,但是结构只包含一个最里层元素。这个结构会将所有匹配元素作为一组包他们最外层。

例子:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

如果我们对inner元素用.wrapAll():

$('.inner').wrapAll('<div class="new" />');

结果如下:

<div class="container">
  <div class="new">
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>
  </div>
</div>

例子:

例子:在所有段落外包上新的div:

<!DOCTYPE html>
<html>
<head>
  <style>

  div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
<script>$("p").wrapAll("<div></div>");</script>

</body>
</html>

Demo:

例子:新建一个元素包住所有span。注意strong里德红色字没有被包住。

<!DOCTYPE html>
<html>
<head>
  <style>

  div { border:2px blue solid; margin:2px; padding:2px; }
  p { background:yellow; margin:2px; padding:2px; }
  strong { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <span>Span Text</span>
  <strong>What about me?</strong>
  <span>Another One</span>
<script>$("span").wrapAll("<div><div><p><em><b></b></em></p></div></div>");</script>

</body>
</html>

Demo:

例子:在所有段落外包上新的div

<!DOCTYPE html>
<html>
<head>
  <style>

  div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
<script>$("p").wrapAll(document.createElement("div"));</script>

</body>
</html>

Demo:

例子:将一个2层的div jQuery对象包在所有段落外面,注意该对象是被复制到目标外层,而不是移动。

<!DOCTYPE html>
<html>
<head>
  <style>

  div { border: 2px solid blue; margin:2px; padding:2px; }
  .doublediv { border-color:red; }
  p { background:yellow; margin:4px; font-size:14px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <div class="doublediv"><div></div></div>
<script>$("p").wrapAll($(".doublediv"));</script>

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订