jquery将当前元素包含在新的父容器中

m.j*_*ohn 5 jquery parent new-operator

我想在当前元素周围使用jquery封装一个新的父容器,类似的东西,但我不喜欢以下行,我想它们并不是真正正确或最佳实践:

this.before('<div id="container">');
this.after('</div>');
// do something with the new parent here
$("#container")...
Run Code Online (Sandbox Code Playgroud)

这样做有更自然的方法吗?谢谢.

phi*_*ash 8

您想使用为此构建的wrap函数!

this.wrap('<div id="container"></div>');
Run Code Online (Sandbox Code Playgroud)

http://api.jquery.com/wrap/


Thi*_*ter 0

是的,.wrap()

示例: http: //jsfiddle.net/ThiefMaster/rPhF2/

<div/>您也可以使用例如<div id="container"/>