[英]How to replace contents of parent element, ignoring children using jQuery
我有一些这样的 HTML:
<div id="demo">
<p>
<span class="myClass">Word test should not be marked</span>
Word test should be marked<br />
</p>
</div>
如何在不包括span
的div
找到一个单词('test')并使用 jQuery 对其进行标记? 我在 SO 等中看到了很多解决方案,但没有一个对我有用。 仅供参考,我尝试使用的代码是这样的:
var regex = XRegExp('test', 'i');
$('#demo').markRegExp(regex);
使用contents()
获取所有子节点,然后迭代和更新文本节点。
$('#demo p') .contents() // get all child nodes including text and comment nodes .each(function() { // iterate over nodes if (this.nodeType == 3) // check node is text node $(this).replaceWith(this.textContent.replace(/test/g, '<span class="test">$&</span>')) // update the content and replace node with html content });
.test { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="demo"> <p> <span class="myClass">Word test should not be marked</span> Word test should be marked <br /> </p> </div>
这是一个繁琐的正则表达式解决方案:
var html=$("#demo").html();
var elements=html.split(/(<[^>]+>)/); // split into tags and text
$.each(elements,function(i,e){
if(!e.match(/<[^>]+>/)){
if(elements[i-1]!==undefined){
if(!$(elements[i-1]).hasClass('myClass')){
elements[i]=elements[i].replace(/test/g,"<span class='highlight'>test</span>");
}
}
}
});
$("#demo").html(elements.join(''));
这将是更清洁,不过,以纪念你想用一个类来代替文字,那么你可以只是做:
$("#demo").find("span[class='myClass']").each(function(){
$(this).html($(this).text().replace(/test/g,"<span class='highlight'>test</span>"));
});
为两种解决方案工作JSFiddle 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.