Get previous node.


/ Published in: JavaScript
Save to your folder(s)

This ignores whitespace and comments.


Copy this code and paste it in your HTML
  1. function getPrevious(el) {
  2. function isIgnorable(node) {
  3. // is a comment or contains only whitespace
  4. return (node.nodeType == 8 || /^[\t\n\r ]+$/.test(node.data));
  5. }
  6.  
  7. var prev = el;
  8. while (prev = prev.previousSibling) {
  9. if (!isIgnorable(prev)) break;
  10. }
  11.  
  12. return prev;
  13. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.