Skip to content

Instantly share code, notes, and snippets.

@steida
Created April 21, 2009 14:36
Show Gist options
  • Save steida/99171 to your computer and use it in GitHub Desktop.
Save steida/99171 to your computer and use it in GitHub Desktop.
function getNearestTextNode(node, forward) {
var body = node.ownerDocument.body,
sibling = forward ? 'nextSibling' : 'previousSibling',
child = forward ? 'firstChild' : 'lastChild',
current = node;
do {
node = current[sibling], current = node || current.parentNode;
if (current == body) return;
}
while (!node);
do {
node = current[child];
if (!node) {
if (current.nodeType == 3) return current;
node = current[sibling];
}
if (!node) {
var tmp = current;
do {
node = tmp.parentNode;
if (node == body) return;
tmp = node, node = node[sibling];
}
while (!node)
}
current = node;
}
while (current != body);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment