Copied from my own answer on a similar thread
This example uses .contents()
to get all the children nodes (including text nodes), then uses .map()
to turn each child node into a string based on the nodeType
. If the node is a text node (i.e. text not within the spans), we return its nodeValue
.
This returns a jQuery set containing strings, so we call .get()
to get a 'standard' array object that we can call .join()
on.
// our 'div' that contains your code:
var $html = $("<div id='attachmentContainer'>\n #Attachment#\n <span id='spnAttachmentName' class='hidden'>#AttachmentName#</span>\n <span id='spnAttachmentPath' class='hidden'>#AttachmentPath#</span>\n</div>");
// Map the contents() into strings
$html.contents().map(function() {
// if the node is a textNode, use its nodeValue, otherwise empty string
return this.nodeType == 3 ? this.nodeValue : '';
// get the array, and join it together:
}).get().join('');
// "
// #Attachment#
//
//
// "
If you want to trim extra whitespace, you can use $.trim(this.nodeValue)
If you need to do this a lot, you could even make a plugin (now with some options):
$.fn.directText = function(settings) {
settings = $.extend({},$.fn.directText.defaults, settings);
return this.contents().map(function() {
if (this.nodeType != 3) return undefined; // remove non-text nodes
var value = this.nodeValue;
if (settings.trim) value = $.trim(value);
if (!value.length) return undefined; // remove zero-length text nodes
return value;
}).get().join(settings.joinText);
};
$.fn.directText.defaults = {
trim: true,
joinText: ''
};