Programming

자식 요소를 변경하지 않고 요소의 텍스트를 어떻게 변경할 수 있습니까?

procodes 2020. 8. 9. 17:41
반응형

자식 요소를 변경하지 않고 요소의 텍스트를 어떻게 변경할 수 있습니까?


요소의 텍스트를 동적으로 업데이트하고 싶습니다.

<div>
   **text to change**
   <someChild>
       text that should not change
   </someChild>
   <someChild>
       text that should not change
   </someChild>
</div>

저는 jQuery를 처음 사용하기 때문에이 작업은 저에게 상당히 어려운 것 같습니다. 누군가가 사용할 기능 / 선택기를 가리킬 수 있습니까?

가능하다면 변경해야 할 텍스트에 대한 새 컨테이너를 추가하지 않고 수행하고 싶습니다.


Mark는 jQuery를 사용하는 더 나은 솔루션을 가지고 있지만 일반 JavaScript에서도이 작업을 수행 할 수 있습니다.

Javascript에서 childNodes속성은 텍스트 노드를 포함하여 요소의 모든 자식 노드를 제공합니다.

따라서 변경하려는 텍스트가 항상 요소의 첫 번째 항목이 될 것이라는 것을 알고 있다면 다음 HTML이 제공됩니다.

<div id="your_div">
   **text to change**
   <p>
       text that should not change
   </p>
   <p>
       text that should not change
   </p>
</div>

다음과 같이 할 수 있습니다.

var your_div = document.getElementById('your_div');

var text_to_change = your_div.childNodes[0];

text_to_change.nodeValue = 'new text';

물론 <div>처음부터 jQuery를 사용하여를 선택할 수 있습니다 (예 :) var your_div = $('your_div').get(0);.


2018 업데이트

이것은 꽤 인기있는 답변이기 때문에 jQuery에 플러그인으로 textnode 선택기를 추가하여 약간 업데이트하고 아름답게하기로 결정했습니다.

아래 스 니펫에서 textNode를 모두 가져 오는 새 jQuery 함수를 정의한 것을 볼 수 있습니다. 이 함수를 예를 들어 함수와 연결할 수도 있습니다 first(). 텍스트 노드에서 트림을 수행하고 공백, 탭, 새 줄 등도 텍스트 노드로 인식되기 때문에 트림 후 비어 있지 않은지 확인합니다. 이러한 노드도 필요하면 jQuery 함수의 if 문에서 간단히 제거하십시오.

첫 번째 텍스트 노드를 바꾸는 방법과 모든 텍스트 노드를 바꾸는 방법에 대한 예제를 추가했습니다.

이 접근 방식을 사용하면 코드를 더 쉽게 읽을 수 있고 다른 용도로 여러 번 사용하기가 더 쉽습니다.

업데이트 2017 (adrach는) 당신이 선호하는 경우 여전히 잘 작동한다.

jQuery.fn.textNodes = function() {
  return this.contents().filter(function() {
    return (this.nodeType === Node.TEXT_NODE && this.nodeValue.trim() !== "");
  });
}

$(document).ready(function(){
  $('#replaceAll').on('click', function() {
    $('#testSubject').textNodes().replaceWith('Replaced');
  });

  $('#replaceFirst').on('click', function() {
    $('#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>


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/


실제보기

마크 업 :

$(function() {
  $('input[type=button]').one('click', function() {
    var cache = $('#parent').children();
    $('#parent').text('Altered Text').append(cache);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">Some text
  <div>Child1</div>
  <div>Child2</div>
  <div>Child3</div>
  <div>Child4</div>
</div>
<input type="button" value="alter text" />


<div id="divtochange">
    **text to change**
    <div>text that should not change</div>
    <div>text that should not change</div>
</div>
$(document).ready(function() {
    $("#divtochange").contents().filter(function() {
            return this.nodeType == 3;
        })
        .replaceWith("changed text");
});

이것은 첫 번째 텍스트 노드 만 변경합니다.


선택할 클래스로 범위에서 변경하려는 텍스트를 래핑하면됩니다.

내가 아는 질문에 반드시 답하는 것은 아니지만 아마도 더 나은 코딩 연습 일 것입니다. 깨끗하고 단순하게 유지하십시오

<div id="header">
   <span class="my-text">**text to change**</span>
   <div>
       text that should not change
   </div>
   <div>
       text that should not change
   </div>
</div>

Voilà!

$('#header .mytext').text('New text here')

언급 한 특정 사례에 대해 :

<div id="foo">
   **text to change**
   <someChild>
       text that should not change
   </someChild>
   <someChild>
       text that should not change
   </someChild>
</div>

... 이것은 매우 쉽습니다.

var div = document.getElementById("foo");
div.firstChild.data = "New text";

이것을 일반화하는 방법을 언급하지 않습니다. 예를 들어에서 첫 번째 텍스트 노드의 텍스트를 변경하려면 <div>다음과 같이 할 수 있습니다.

var child = div.firstChild;
while (child) {
    if (child.nodeType == 3) {
        child.data = "New text";
        break;
    }
    child = child.nextSibling;
}

$.fn.textPreserveChildren = function(text) {
  return this.each(function() {
    return $(this).contents().filter(function() {
      return this.nodeType == 3;
    }).first().replaceWith(text);
  })
}

setTimeout(function() {
  $('.target').textPreserveChildren('Modified');
}, 2000);
.blue {
  background: #77f;
}
.green {
  background: #7f7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<div class="target blue">Outer text
  <div>Nested element</div>
</div>

<div class="target green">Another outer text
  <div>Another nested element</div>
</div>


Here is yet another method : http://jsfiddle.net/qYUBp/7/

HTML

<div id="header">
   **text to change**
   <div>
       text that should not change
   </div>
   <div>
       text that should not change
   </div>
</div>

JQUERY

var tmp=$("#header>div").html();
$("#header").text("its thursday").append(tmp);

Lots of great answers here but they only handle one text node with children. In my case I needed to operate on all text nodes and ignore html children BUT PRESERVE THE ORDERING.

So if we have a case like this:

<div id="parent"> Some text
    <div>Child1</div>
    <div>Child2</div>
    and some other text
    <div>Child3</div>
    <div>Child4</div>
    and here we are again
</div>

We can use the following code to modify the text only AND PRESERVE THE ORDERING

    $('#parent').contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE && this.nodeValue.trim() != '';
    }).each(function() {
    		//You can ignore the span class info I added for my particular application.
        $(this).replaceWith(this.nodeValue.replace(/(\w+)/g,"<span class='IIIclassIII$1' onclick='_mc(this)' onmouseover='_mr(this);' onmouseout='_mt(this);'>$1X</span>"));
	});
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div id="parent"> Some text
    <div>Child1</div>
    <div>Child2</div>
    and some other text
    <div>Child3</div>
    <div>Child4</div>
    and here we are again
</div>

Here is the jsfiddle of it working


I think you're looking for .prependTo().

http://api.jquery.com/prependTo/

We can also select an element on the page and insert it into another:

$('h2').prependTo($('.container'));

If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):

<div class="container">  
  <h2>Greetings</h2>
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div> 
</div>

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.


Simple answer:

$("div").contents().filter(function(){ 
  return this.nodeType == 3; 
})[0].nodeValue = "The text you want to replace with"

Problem with Mark's answer is that you get empty textnodes aswell. Solution as jQuery plugin:

$.fn.textnodes = function () {
    return this.contents().filter(function (i,n) {
        return n.nodeType == 3 && n.textContent.trim() !== "";
    });
};

$("div").textnodes()[0] = "changed text";

This is an old question but you can make a simple function like this to make your life easier:

$.fn.toText = function(str) {
    var cache = this.children();
    this.text(str).append(cache);
}

Example:

<div id="my-div">
   **text to change**
   <p>
       text that should not change
   </p>
   <p>
       text that should not change
   </p>
</div>

Usage:

$("#my-div").toText("helloworld");

2019 vesrsion - Short & Simple

document.querySelector('#your-div-id').childNodes[0].nodeValue = 'new text';

Explanation

document.querySelector('#your-div-id') is used for selecting the parent (the element which text you are about to change)

.childNodes[0] selects the text node

.nodeValue = 'new text' sets text node value to "new text"


This answer is possibly inspired by Dean Martin's comment. Can't say for sure since I've been using this solution for years now. Just thought I should post this probability here because some people care about it more than the fact that this is the best solution.

참고URL : https://stackoverflow.com/questions/4106809/how-can-i-change-an-elements-text-without-changing-its-child-elements

반응형