data-color =“ red”我要在span标记之前和之后2个字。
这是我的html代码:
<p>This pathway has an inner and an outer wall. The pressure <span data-color="red" class="highlight">inside the</span> eye closes the tunnel.</p>
我想要这样的输出=>
The pressure <span data-color="red" class="highlight">inside the</span> eye closes
注意:范围标记中的属性会更改
您可以获取该.highlight
元素的上一个和下一个同级,并对textNodes进行切片:
function get(el, dir) {
var ps = el[dir === 'prev' ? 'previousSibling' : 'nextSibling'];
if (!ps || ps.nodeType !== 3) return '';
var arr = ps.nodeValue.trim().split(/\s+/g);
return dir == 'prev'
? arr.slice(-2).join(' ')
: arr.slice(0, 2).join(' ');
}
$('p').has('.highlight').html(function () {
var e = $('.highlight', this).get(0);
return get(e, 'prev') + ' ' + e.outerHTML + ' ' + get(e, 'next');
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句