You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
834 B
JavaScript

"use strict";
function findIdRoot(element) {
let current = element;
while (current != null) {
if (current.id != null && current.id !== "") {
return current;
} else {
current = current.parentElement;
}
}
}
module.exports = function generateSelector(element) {
/* FIXME: check that element != null */
let root = findIdRoot(element);
if (root === element) {
/* Special case: always identify by the ID alone, never suffix anything else, when the selected element *itself* has an ID. */
return `#${element.id}`;
} else {
let segments = [
(root != null) ? `#${root.id}` : null,
(element.classList.length > 0)
? Array.from(element.classList).map((className) => `.${className}`).join("")
: element.tagName.toLowerCase()
].filter((segment) => segment != null);
return segments.join(" ");
}
};