使用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。
答案 0 :(得分:2)
您可以过滤strong
元素,返回它及其兄弟文本节点。在附加文本后,从相邻文本节点中删除文本,然后包装返回的元素:
$('.some-name strong').filter(function () {
$(this).append(this.nextSibling.nodeValue);
this.nextSibling.nodeValue = '';
return $(this);
}).wrap('<div class="wrap"></div>');
如果希望在strong
元素被包装后附加文本节点:
$('.some-name strong').wrap('<div class="wrap"></div>');
$('.some-name .wrap').each(function () {
$(this).append(this.nextSibling.nodeValue);
this.nextSibling.nodeValue = '';
});