From b515eaa076ed9a6cb5e19bf2e735a848fa5456fb Mon Sep 17 00:00:00 2001 From: Eric Lippmann Date: Mon, 18 Jan 2016 10:54:33 +0100 Subject: [PATCH] JS: Introduce getCSSPath getCSSPath returns the CSS path to a given jQuery element. We have getDomPath which is not robust enough and getElementByDomPath which makes no sense because getDomPath could already return a selector suitable for jQuery. getCSSPath is meant to replace both of them. The function is far from perfect, as its lacking class consideration and optimization. --- public/js/icinga/utils.js | 51 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/public/js/icinga/utils.js b/public/js/icinga/utils.js index cca01d061..fa62dfabf 100644 --- a/public/js/icinga/utils.js +++ b/public/js/icinga/utils.js @@ -269,6 +269,57 @@ } }, + /** + * Get the CSS selector to the given node + * + * @param {jQuery} $node + * + * @returns {string} + */ + getCSSPath: function($node) { + if (! $node.length) { + throw 'Requires a node'; + } + + var path = []; + + while (true) { + var id = $node.attr('id'); + + if (typeof id !== 'undefined') { + path.push('#' + id); + break; + } + + var tagName = $node.prop('tagName').toLowerCase(); + //var classes = $node.attr('class'); + // + //if (classes) { + // classes = classes.split(' ').join('.'); + //} + + var $parent = $node.parent(); + + if (! $parent.length) { + path.push(tagName); + break; + } + + var $siblings = $parent.children(tagName); + + if ($siblings.length > 1) { + var index = $siblings.index($node) + 1; + path.push(tagName + ':nth-of-type(' + index.toString() + ')'); + } else { + path.push(tagName); + } + + $node = $parent; + } + + return path.reverse().join(' > '); + }, + /** * Climbs up the given dom path and returns the element *