Say I have the following code:
<div>
Some text
<h1>A divider</h1>
More text
</div>
[Preferably] via jQuery, how would I grab "More text" and replace it?
Say I have the following code:
<div>
Some text
<h1>A divider</h1>
More text
</div>
[Preferably] via jQuery, how would I grab "More text" and replace it?
jQuery 并不能很好地支持 textnodes,但是像 nextSibling 这样的原生 JS 可以:
$('div h1').get(0).nextSibling.nodeValue = 'New text';
使用.contents()
,您可以查看子文本节点,然后使用String.prototype.replace
替换该文本。就像是:
$("div").contents().each(function () {
if (this.nodeType === 3) {
this.nodeValue = this.nodeValue.replace("More text", "Some new text");
}
});
演示:http: //jsfiddle.net/uYJzM/
这是对“更多文本”的非常宽松的检查,因为它实际上取决于您想要做什么。
参考: