so_getText

Summary

Returns a string of all text found in obj.

Arguments:

HTMLObject obj
The parent element to parse the text from.

Usage:

var txt = so_getText(document.getElementById("mContainer");

Examples:

This is fairly self explanatory -- pass it a handle to an object and it will pass back a string with the values of all the text nodes that decend from that object and that objects children. Essentially a DOM based version of MSIE's innerText.

Update 02.04.2006: Added DOM3 textContent check per Steve Clay's suggestion.

Code

function so_getText(obj) {
	if(obj.textContent) return obj.textContent;
	if (obj.nodeType == 3) return obj.data;
	var txt = new Array(), i=0;
	while(obj.childNodes[i]) {
		txt[txt.length] = so_getText(obj.childNodes[i]);
		i++;
	}
    return txt.join("");
}

License

This code is issued under a Creative Commons license. You do not need my permission to use it, though I'm always interested in seeing where my code has ended up if you want to drop me a line.

slayeroffice main