2018 업데이트
이것은 꽤 인기있는 답변이기 때문에 jQuery에 플러그인으로 textnode 선택기를 추가하여 약간 업데이트하고 아름답게하기로 결정했습니다.
아래 스 니펫에서 textNode를 모두 가져 오는 새 jQuery 함수를 정의한 것을 볼 수 있습니다. 이 함수를 예를 들어 함수와 연결할 수도 있습니다 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) 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/