Jquery在html和纯文本中查找模式

时间:2015-02-09 00:24:26

标签: javascript jquery

使用jQuery转换此

的最佳方法是什么
<div class="some-name">
   <strong>8</strong>
   views
   <strong>2</strong>
   likes
</div>

<div class="some-name">
   <div class="wrap">
     <strong>8</strong>
     views
   </div>
   <div class="wrap">
     <strong>2</strong>
     likes
   </div>
</div>

我正试图包装这种模式

<strong>some text</strong>
some text
<{1>}中的

但不确定将<div class="wrap"></div>&gt;分组的最佳方式是哪种和纯文本对。

注意:在使用Jquery之前,我无法更改HTML。

1 个答案:

答案 0 :(得分:2)

您可以过滤strong元素,返回它及其兄弟文本节点。在附加文本后,从相邻文本节点中删除文本,然后包装返回的元素:

Example Here

$('.some-name strong').filter(function () {
    $(this).append(this.nextSibling.nodeValue);
    this.nextSibling.nodeValue = '';
    return $(this);
}).wrap('<div class="wrap"></div>');

如果希望在strong元素被包装后附加文本节点:

Updated Example

$('.some-name strong').wrap('<div class="wrap"></div>');
$('.some-name .wrap').each(function () {
    $(this).append(this.nextSibling.nodeValue);
    this.nextSibling.nodeValue = '';
});