找到文本节点 () 并替换 :nodeType==3
textContent
$('#one').contents().filter(function() {
return this.nodeType == 3
}).each(function(){
this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
请注意,根据文档,您可以替换上面中的硬编码,这样可以更清楚地说明您在做什么。3
Node.TEXT_NODE
$('#one').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).each(function(){
this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">
<div class="first"></div>
"Hi I am text"
<div class="second"></div>
<div class="third"></div>
</div>