Оновлення 2018 року
Оскільки це досить популярна відповідь, я вирішив її трохи оновити та прикрасити, додавши селектор текстових вузлів до jQuery як плагін.
У фрагменті нижче ви бачите, що я визначаю нову функцію jQuery, яка отримує всі (і лише) текстові вузли. Цю функцію можна пов'язати також, наприклад, з first()функцією. Я обробляю текстовий вузол і перевіряю, чи не порожній він після обрізки, оскільки пробіли, вкладки, нові рядки тощо також розпізнаються як текстові вузли. Якщо вам потрібні ці вузли, просто видаліть їх з оператора if у функції jQuery.
Я додав приклад, як замінити перший текстовий вузол і як замінити всі текстові вузли.
Такий підхід полегшує читання коду та простіше використовувати його кілька разів та з різною метою.
Update 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) eqivilant
//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/