Suppose that you want to change the text of an element without touching its descendant elements. Unfortunately, the jQuery's text()
method actually affects also the children elements of a target element. But there's a solution.
We can define the following plugin that takes care only of text nodes:
(function ($) {
$.fn.smartext = function (text) {
var that = this,
element = this[0],
children = element.childNodes;
if (children.length > 0) {
var textNodes = [];
for (var i = 0; i < children.length; i++) {
var node = children[i];
if (node.nodeType == 3 && !/^\s+$/.test(node.nodeValue)) {
textNodes.push(node);
}
}
for (var j = 0; j < textNodes.length; j++) {
var textNode = textNodes[j];
var textN = document.createTextNode(text);
element.replaceChild(textN, textNode);
}
} else {
that.text(text);
}
return that;
};
})(jQuery);
Our plugin collects only children nodes which are text nodes and are not empty. An example:
$(function () {
$('#text').on('click', function () {
$('#test').smartext('Foo');
});
});
[view-example url="http://jsfiddle.net/gabrieleromanato/4h2V3/"]