Shouldn't be much harder than
node.firstChild && node.firstChild.nodeType === Node.TEXT_NODE ||
node.lastChild && node.lastChild.nodeType === Node.TEXT_NODE
For readability, it is better to use the Node.*_NODE
symbolic constants (although they might not be defined in older browsers).
To avoid problems with empty text nodes you might precede this with a
node.normalize()
which
Puts the specified node and all of its subtree into a "normalized"
form. In a normalized subtree, no text nodes in the subtree are empty
and there are no adjacent text nodes.
See https://developer.mozilla.org/en-US/docs/Web/API/Node.normalize.
To omit comment nodes and whitespace-only text nodes:
var children = Array.prototype.filter.call(node.childNodes || [], function(node) {
return node.nodeType !== Node.COMMENT_NODE &&
(node.nodeType !== Node.TEXT_NODE || /\S/.test(node.nodeValue));
}),
firstChild = children[0],
lastChild = children[children.length-1];
return firstChild && firstChild.nodeType === Node.TEXT_NODE ||
lastChild && lastChild.nodeType === Node.TEXT_NODE;
If for some reason it's important to check that there is a child element lurking inside then it would suffice to add a check for
!!node.children.length