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

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

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

I'm new to jQuery, so this task seems to be quite challenging for me. Could someone point me to a function/selector to use?

If it is possible, I'd like to do it without adding a new container for the text I need to change.


Solution 1:

Mark’s got a better solution using jQuery, but you might be able to do this in regular JavaScript too.

In Javascript, the childNodes property gives you all the child nodes of an element, including text nodes.

So, if you knew the text you wanted to change was always going to be the first thing in the element, then given e.g. this HTML:

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

You could do this:

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

var text_to_change = your_div.childNodes[0];

text_to_change.nodeValue = 'new text';

Of course, you can still use jQuery to select the <div> in the first place (i.e. var your_div = $('your_div').get(0);).

Solution 2:

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/

Solution 3:

See In action

Markup :

$(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" />

Solution 4:

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

Solution 5:

<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