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

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);).


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/


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