Обновление 2018
Поскольку это довольно популярный ответ, я решил немного обновить и украсить его, добавив селектор текстового узла в jQuery в качестве плагина.
Во фрагменте ниже вы можете видеть, что я определяю новую функцию jQuery, которая получает все (и только) textNodes. Вы можете связать эту функцию, например, с 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)
//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 (адрах):
Похоже, с тех пор, как это было опубликовано, несколько вещей изменились. Вот обновленная версия
$("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/