更新2018
由于这是一个非常受欢迎的答案,因此我决定通过将textnode选择器作为插件添加到jQuery中来对其进行一些更新和美化。
在下面的代码段中,您可以看到我定义了一个新的jQuery函数,该函数将获取所有(且仅)textNodes。您也可以使用例如该first()功能链。我在文本节点上进行修剪,并检查修剪后它是否不为空,因为空格,制表符,换行等也被识别为文本节点。如果您也需要这些节点,则只需将其从jQuery函数的if语句中删除即可。
我添加了一个示例,该示例如何替换第一个文本节点以及如何替换所有文本节点。
这种方法使读取代码更容易,并且可以多次将其用于不同目的。
将更新2017年(adrach)如果你喜欢的应该仍然正常工作。
作为jQuery扩展
//Add a jQuery extension so it can be used on any jQuery object
jQuery.fn.textNodes = function() {
return this.contents().filter(function() {
return (this.nodeType === Node.TEXT_NODE && this.nodeValue.trim() !== "");
});
}
//Use the jQuery extension
$(document).ready(function(){
$('#replaceAll').on('click', () => {
$('#testSubject').textNodes().replaceWith('Replaced');
});
$('#replaceFirst').on('click', () => {
$('#testSubject').textNodes().first().replaceWith('Replaced First');
});
});
p {
margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testSubject">
**text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**also text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**last text to change**
</div>
<button id="replaceFirst">Replace First</button>
<button id="replaceAll">Replace All</button>
Javascript(ES)功能
//Add a new function to the HTMLElement object so it cna be used on any HTMLElement
HTMLElement.prototype.textNodes = function() {
return [...this.childNodes].filter((node) => {
return (node.nodeType === Node.TEXT_NODE && node.nodeValue.trim() !== "");
});
}
//Use the new HTMLElement function
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#replaceAll').addEventListener('click', () => {
document.querySelector('#testSubject').textNodes().forEach((node) => {
node.textContent = 'Replaced';
});
});
document.querySelector('#replaceFirst').addEventListener('click', function() {
document.querySelector('#testSubject').textNodes()[0].textContent = 'Replaced First';
});
});
p {
margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testSubject">
**text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**also text to change**
<p>text that should not change</p>
<p>text that should not change</p>
**last text to change**
</div>
<button id="replaceFirst">Replace First</button>
<button id="replaceAll">Replace All</button>
更新2017(adrach):
自发布以来,似乎发生了一些变化。这是更新版本
$("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("change text");
原始答案(不适用于当前版本)
$("div").contents().filter(function(){ return this.nodeType == 3; })
.filter(':first').text("change text");
资料来源:http://api.jquery.com/contents/