How can I change an element's text without changing its child elements?

前端 未结 14 2085
难免孤独
难免孤独 2020-11-22 07:30

I\'d like to update element\'s text dynamically:

**text to change** text t
相关标签:
14条回答
  • 2020-11-22 08:14
    <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");
    });
    

    This changes only the first textnode

    0 讨论(0)
  • 2020-11-22 08:15

    Update 2018

    Since this is a pretty popular answer I decided to update and beautify it a little by adding the textnode selector to jQuery as a plugin.

    In the snippet below you can see that I define a new jQuery function that gets all (and only) the textNodes. You can chain of this function as well with for example the first() function. I do a trim on the text node and check if it's not empty after the trim because spaces, tabs, new lines, etc. are also recognized as text nodes. If you need those nodes too then simple remove that from the if statement in the jQuery function.

    I added an example how to replace first text node and how to replace all text nodes.

    This approach makes it easier to read the code and easier to use it multiple times and with different purposes.

    The Update 2017 (adrach) should still work as well if you prefer that.

    As jQuery extension

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


    Update 2017 (adrach):

    It looks like several things changed since this was posted. Here is an updated version

    $("div").contents().filter(function(){ return this.nodeType == 3; }).first().replaceWith("change text");
    

    Original answer (Not working for current versions)

    $("div").contents().filter(function(){ return this.nodeType == 3; })
    .filter(':first').text("change text");
    

    Source: http://api.jquery.com/contents/

    0 讨论(0)
  • 2020-11-22 08:16

    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);
    
    0 讨论(0)
  • 2020-11-22 08:17

    Simple answer:

    $("div").contents().filter(function(){ 
      return this.nodeType == 3; 
    })[0].nodeValue = "The text you want to replace with"
    
    0 讨论(0)
  • 2020-11-22 08:21

    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");
    
    0 讨论(0)
  • 2020-11-22 08:23

    Just wrap the text you want to change in a span with a class to select.

    Doesn't necessarily answer your question I know, but, probably a better coding practice. Keep things clean and simple

    <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')
    
    0 讨论(0)
提交回复
热议问题