我有一个 div,我将其替换为文本区域,例如:
var $targetDiv = $('#the-div');
var $newDiv = $('#the-new-div');
$targetDiv.replaceWith($newDiv);
这会变成:
<div id="the-div"></div>
进入:
<div id="the-new-div"></div>
我该如何包装<div id="the-new-div"></div>
在名为 <div id="the-new-div-wrapper">
的 div 中?
所以结果会变成:
<div id="the-new-div-wrapper">
<div id="the-new-div">
</div>
</div>
$targetDiv.replaceWith($newDiv).wrap('<div id="the-new-div-wrapper"' />')
似乎不起作用。
最佳答案
先包起来
$targetDiv.wrap('<div id="the-new-div-wrapper" />').replaceWith($newDiv);
或者将其分成两行:
$targetDiv.replaceWith($newDiv);
$newDiv.wrap('<div id="the-new-div-wrapper" />');
您的代码中还有一个拼写错误:$targetDiv.replaceWith($newDiv).wrap('<div id="the-new-div-wrapper"' />')
多了一个不应该出现的撇号。
关于javascript - 如何替换 DOM 节点并将其包装起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10121325/