wrapAll不包装纯文本

时间:2014-10-15 19:43:14

标签: javascript jquery

有些HTML看起来像这样:

  <body>
    Do
    all
    declarations for
    the same
    <TT>static</TT> function
    or variable
    have to include the storage class <TT>static</TT>?
  </body>

当我$('body').children().wrapAll("<div class='container'><div class='row'><div class='col-md-12'></div></div></div>");将所有内容都包装到.container中时,它会起作用,除非它不包含纯文本:

  <body>
   <div class='container'>
    <div class='row'>
     <div class='col-md-12'>
      <TT>static</TT>
      <TT>static</TT>
     </div>
    </div>
   </div>
    Do
    all
    declarations for
    the same
    function
    or variable
    have to include the storage class ?
  </body>

如何修复此问题以保留原始结构?

1 个答案:

答案 0 :(得分:2)

children不返回文本节点。您需要使用contents

$('body').contents().wrapAll("<div class='container'><div class='row'><div class='col-md-12'></div></div></div>");

&#13;
&#13;
$(function(){
  $('#children').children().wrapAll("<div class='container'><div class='row'><div class='col-md-12'></div></div></div>");

  $('#contents').contents().wrapAll("<div class='container'><div class='row'><div class='col-md-12'></div></div></div>");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h2>With Children:</h2>
<div id="children">
Do
    all
    declarations for
    the same
    <TT>static</TT> function
    or variable
    have to include the storage class <TT>static</TT>?
 </div>

<h2>With Contents:</h2>
<div id="contents">
Do
    all
    declarations for
    the same
    <TT>static</TT> function
    or variable
    have to include the storage class <TT>static</TT>?
 </div>
&#13;
&#13;
&#13;