This answer will work to get only text for any HTML element.
This first โnodeโ parameter is an element for receiving text. The second parameter is optional, and if true will add a space between the text inside the elements, if there was no space.
function getTextFromNode(node, addSpaces) { var i, result, text, child; result = ''; for (i = 0; i < node.childNodes.length; i++) { child = node.childNodes[i]; text = null; if (child.nodeType === 1) { text = getTextFromNode(child, addSpaces); } else if (child.nodeType === 3) { text = child.nodeValue; } if (text) { if (addSpaces && /\S$/.test(result) && /^\S/.test(text)) text = ' ' + text; result += text; } } return result; }
James 05 Sep '14 at 19:32 2014-09-05 19:32
source share