If I have html like this:
This is some text
First span text
Simple answer:
$("#listItem").contents().filter(function(){
return this.nodeType == 3;
})[0].nodeValue = "The text you want to replace with"
This is an old question but the top answer is very inefficient. Here's a better solution:
$.fn.myText = function() {
var str = '';
this.contents().each(function() {
if (this.nodeType == 3) {
str += this.textContent || this.innerText || '';
}
});
return str;
};
And just do this:
$("#foo").myText();
You can try this
alert(document.getElementById('listItem').firstChild.data)
Using plain JavaScript in IE 9+ compatible syntax in just a few lines:
let children = document.querySelector('#listItem').childNodes;
if (children.length > 0) {
childrenLoop:
for (var i = 0; i < children.length; i++) {
//only target text nodes (nodeType of 3)
if (children[i].nodeType === 3) {
//do not target any whitespace in the HTML
if (children[i].nodeValue.trim().length > 0) {
children[i].nodeValue = 'Replacement text';
//optimized to break out of the loop once primary text node found
break childrenLoop;
}
}
}
}
Similar to the accepted answer, but without cloning:
$("#foo").contents().not($("#foo").children()).text();
And here is a jQuery plugin for this purpose:
$.fn.immediateText = function() {
return this.contents().not(this.children()).text();
};
Here is how to use this plugin:
$("#foo").immediateText(); // get the text without children
I liked this reusable implementation based on the clone()
method found here to get only the text inside the parent element.
Code provided for easy reference:
$("#foo")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();