在h2标记内的特定元素和文本节点周围包裹span元素

时间:2016-01-13 15:31:19

标签: jquery html css

是否可以使用jQuery执行以下操作,以便:

<h2>
    This is a test 
    <span>i</span>
    mag
    <span>i</span>
    nat
    <span>i</span>
    on  
</h2>

成为这个:

<h2>
    This is a test 
    <span class="wrap">
       <span>i</span>
       mag
       <span>i</span>
       nat
       <span>i</span>
       on   
    </span>
</h2>

所以我希望外跨度包裹所有内跨。

不要觉得这是一个重复的问题,因为我想要包装所有跨度而不是文本&#34;这是一个测试&#34;。

2 个答案:

答案 0 :(得分:4)

您需要使用$.wrapAll()

$(function () {
  $("h2 span").wrapAll('<span class="wrap" />');
});
.wrap {background: #ccf;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>
  This is a test 
  <span>Test</span>
  <span>Test</span>
  <span>Test</span>   
</h2>

答案 1 :(得分:2)

根据您的更新,您可以根据h2this元素还是span是{{1}来过滤this.previousSibling元素的内容元素:

&#13;
&#13;
span
&#13;
$('h2').contents().filter(function () {
  return $(this).is('span') || $(this.previousSibling).is('span');
}).wrapAll('<span class="wrap" />');
&#13;
.wrap { color: #f00; }
&#13;
&#13;
&#13;

或者,您也可以过滤元素和文本节点,并使用等于&#39;这是测试的修剪文本排除文本节点:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>
    This is a test 
    <span>i</span>
    mag
    <span>i</span>
    nat
    <span>i</span>
    on  
</h2>
&#13;
$('h2').contents().filter(function () {
  return this.textContent.trim() !== 'This is a test';
}).wrapAll('<span class="wrap" />');
&#13;
.wrap { color: #f00; }
&#13;
&#13;
&#13;

您也可以只排除第一个文本节点:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>
    This is a test 
    <span>i</span>
    mag
    <span>i</span>
    nat
    <span>i</span>
    on  
</h2>
&#13;
$('h2').contents().filter(function () {
  return this !== this.parentElement.firstChild;
}).wrapAll('<span class="wrap" />');
&#13;
.wrap { color: #f00; }
&#13;
&#13;
&#13;

相关问题