programing

하위 요소를 변경하지 않고 요소의 텍스트를 변경하려면 어떻게 해야 합니까?

kingscode 2023. 8. 9. 22:03
반응형

하위 요소를 변경하지 않고 요소의 텍스트를 변경하려면 어떻게 해야 합니까?

요소의 텍스트를 동적으로 업데이트합니다.

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

저는 jQuery가 처음이라 이 일은 저에게 꽤 어려운 일인 것 같습니다.누가 사용할 기능/선택기를 알려주시겠습니까?

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

Mark는 jQuery를 사용하여 더 나은 솔루션을 제공하지만 일반 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';

하여 물론, 당를히 jQuery다사용여하있수니습택선할여를 할 수도 .<div> 애에즉초즉▁(에,,var your_div = $('your_div').get(0);).

2018년 업데이트

이것이 꽤 인기 있는 답변이기 때문에 저는 텍스트 노드 선택기를 jQuery에 플러그인으로 추가하여 약간 업데이트하고 미화하기로 결정했습니다.

아래의 스니펫에서 당신은 내가 모든 (그리고 오직) textNodes를 얻는 새로운 jQuery 함수를 정의하는 것을 볼 수 있습니다.예를 들어 이 함수를 연결할 수도 있습니다.first()例능.합니다.공백, 탭, 새 줄 등도 텍스트 노드로 인식되기 때문에 텍스트 노드에서 트림을 하고 트림 후 비어 있지 않은지 확인합니다.이러한 노드도 필요한 경우 jQuery 함수의 if 문에서 해당 노드를 제거하기만 하면 됩니다.

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

이 방법을 사용하면 코드를 더 쉽게 읽을 수 있고 여러 번 다른 목적으로 코드를 더 쉽게 사용할 수 있습니다.

원하는 경우에도 업데이트 2017(접근)이 작동합니다.

As 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 can 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/

사용 중 보기

마크업:

$(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="header">
   <span class="my-text">**text to change**</span>
   <div>
       text that should not change
   </div>
   <div>
       text that should not change
   </div>
</div>

Voila!

$('#header .mytext').text('New text here')
<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="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>

간단한 대답:

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

다른 방법은 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);

Mark의 대답의 문제는 빈 텍스트 노드도 있다는 것입니다.jQuery 플러그인 솔루션:

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

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

여기에는 많은 훌륭한 답변들이 있지만 그들은 아이들이 있는 하나의 텍스트 노드만 처리합니다.나의 경우 모든 텍스트 노드에서 작동하고 HTML 자식은 무시하지만 순서는 유지해야 했습니다.

만약 이런 경우가 있다면,

<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>

다음 코드를 사용하여 텍스트만 수정하고 주문을 보존할 수 있습니다.

    $('#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>

여기 작동하는 jsfidle입니다.

.prependTo()를 찾으시는 것 같습니다.

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

페이지에서 요소를 선택하여 다른 요소에 삽입할 수도 있습니다.

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

이 방법으로 선택한 요소를 다른 곳에 삽입하면 해당 요소가 대상(복제되지 않음)으로 이동합니다.

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

그러나 대상 요소가 둘 이상인 경우 삽입된 요소의 복제된 복사본이 첫 번째 이후 각 대상에 대해 만들어집니다.

이것은 오래된 질문이지만 당신은 당신의 삶을 더 쉽게 만들기 위해 다음과 같은 간단한 기능을 만들 수 있습니다.

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

예:

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

용도:

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

2019 version - Short & Simple

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

설명.

document.querySelector('#your-div-id')부모(변경하려는 텍스트 요소)를 선택하는 데 사용됩니다.

.childNodes[0]텍스트 노드를 선택합니다.

.nodeValue = 'new text'텍스트 노드 값을 "새 텍스트"로 설정합니다.


이 대답은 아마도 딘 마틴의 논평에서 영감을 받았을 것입니다.몇 년 동안 이 솔루션을 사용했기 때문에 확실하게 말할 수 없습니다.어떤 사람들은 이것이 최고의 해결책이라는 사실보다 더 신경을 쓰기 때문에 이 확률을 여기에 올려야 한다고 생각했습니다.

Javascript 접근법. 부모 div를 선택하면 첫 번째 Child.textContent를 사용할 수 있습니다.

let myDiv = document.getElementById("parentDiv");
myDiv.firstChild.textContent = "** New Text **"

재귀적인 방법은 다음과 같습니다.

function changeInnerText(elm,text,newText) {
    if (elm == null) {
        return;
    }
    changeInnerTextHelper(elm.firstChild, text, newText);
}
function changeInnerTextHelper(elm, text, newText) {
    if (elm == null) {
        return;
    }
    if (elm.nodeType == 3 && elm.data == text) {
        elm.data = newText;
        return;
    }
    changeInnerTextHelper(elm.firstChild, text, newText);
    changeInnerTextHelper(elm.nextSibling, text, newText);
}

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

반응형