[英]get previous 2 and next 2 words of span tag in jquery
data-color="red"I want 2 words after and before span tags. data-color =“red”我想在span标签之前和之后2个单词。
here is my html code: 这是我的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>
I want output like this=> 我想输出像这样=>
The pressure <span data-color="red" class="highlight">inside the</span> eye closes
note: attributes in span tags changes 注意: span标记中的属性会发生变化
You could get the previous and next sibling of the .highlight
element and slice the textNodes: 您可以获取.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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.