Added a helper function to return the closest element
authorAlexander Ebert <ebert@woltlab.com>
Thu, 9 Nov 2017 19:20:21 +0000 (20:20 +0100)
committerAlexander Ebert <ebert@woltlab.com>
Thu, 9 Nov 2017 19:20:27 +0000 (20:20 +0100)
wcfsetup/install/files/js/wcf.globalHelper.js

index 48fdc94474de40e43d506a5ed9e11cf80230bf7c..e0c8b07db5cb2ab3390171024b296a53bddaa11c 100644 (file)
                return document.createElement(tagName);
        };
        
+       /**
+        * Returns the closest element (parent for text nodes), optionally matching
+        * the provided selector.
+        * 
+        * @param       {Node}          node            start node
+        * @param       {string=}       selector        optional CSS selector
+        * @return      {Element}       closest matching element
+        */
+       window.elClosest = function (node, selector) {
+               if (!(node instanceof Node)) {
+                       throw new TypeError('Provided element is not a Node.');
+               }
+               
+               // retrieve the parent element for text nodes
+               if (node.nodeType === Node.TEXT_NODE) {
+                       node = node.parentNode;
+                       
+                       // text node had no parent
+                       if (node === null) return null;
+               }
+               
+               if (typeof selector !== 'string') selector = '';
+               
+               if (selector.length === 0) return node;
+               
+               return node.closest(selector);
+       };
+       
        /**
         * Shorthand function to retrieve or set a 'data-' attribute.
         *