找到文本节点 ( 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>