js: Make Utils.getCSSPath work without a jQuery set

This commit is contained in:
Johannes Meyer 2021-03-30 09:30:55 +02:00
parent 25263e767b
commit 1675cc6d74

View File

@ -351,50 +351,56 @@
/** /**
* Get the CSS selector to the given node * Get the CSS selector to the given node
* *
* @param {jQuery} $node * @param {HTMLElement} element
* *
* @returns {string} * @returns {string}
*/ */
getCSSPath: function($node) { getCSSPath: function(element) {
if (! $node.length) { if (typeof element === 'undefined') {
throw 'Requires a node'; throw 'Requires a element';
}
if (typeof element.jquery !== 'undefined') {
if (! element.length) {
throw 'Requires a element';
}
element = element[0];
} }
var path = []; var path = [];
while (true) { while (true) {
var id = $node.attr('id'); var id = element.id;
// Ignore forms and form controls because id generation is unreliable :( // Ignore forms and form controls because id generation is unreliable :(
if (typeof id !== 'undefined' && ! $node.is(':input') && ! $node.is('form')) { if (id && ! element.form && ! (element instanceof HTMLFormElement)) {
path.push('#' + id); path.push('#' + id);
break; break;
} }
var tagName = $node.prop('tagName').toLowerCase(); var tagName = element.tagName;
//var classes = $node.attr('class'); var parent = element.parentElement;
//
//if (classes) {
// classes = classes.split(' ').join('.');
//}
var $parent = $node.parent(); if (! parent) {
path.push(tagName.toLowerCase());
if (! $parent.length) {
path.push(tagName);
break; break;
} }
var $siblings = $parent.children(tagName); if (parent.children.length) {
var index = 0;
do {
if (element.tagName === tagName) {
index++;
}
} while ((element = element.previousElementSibling));
if ($siblings.length > 1) { path.push(tagName.toLowerCase() + ':nth-of-type(' + index + ')');
var index = $siblings.index($node) + 1;
path.push(tagName + ':nth-of-type(' + index.toString() + ')');
} else { } else {
path.push(tagName); path.push(tagName.toLowerCase());
} }
$node = $parent; element = parent;
} }
return path.reverse().join(' > '); return path.reverse().join(' > ');