我需要将“快捷输入”的所有实例更改为"<a href="link">Express Entry</a>"
,而忽略链接中已经存在的所有文本
这就是我所拥有的:
$('.news article p').each(function() {
var text = $(this).html();
if ( ignore anything wrapped in an <a> tag ) {
$(this).html(text.replace('Express Entry', '<a href="https://www.ackahlaw.com/resources/check-your-express-entry-score">Express Entry</a>'));
}
});
我已经尝试过使用contents()和nodeType,但是还不太清楚如何使它工作...
答案 0 :(得分:2)
.contents()获取匹配的元素集中每个元素的子元素,包括文本和注释节点。
您需要按nodeType进行过滤:
$('.news article p').each(function() {
$('.news article p').contents().each(function(idx, ele) {
if (ele.nodeType == Node.TEXT_NODE) { // if text node.....
var newele = ele.textContent.replace('Express Entry',
'<a href="https://www.ackahlaw.com/resources/check-your-express-entry-score">Express Entry</a>');
$(ele).replaceWith(newele)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="news">
<article>
<p>text1 <a href="link">Express Entry</a> text2 Express Entry text3</p>
<p>text4 <a href="link">Express Entry</a> text5 Express Entry text5</p>
</article>
</div>