Skip to content

Instantly share code, notes, and snippets.

@myfreeer
Last active March 8, 2018 10:04
Show Gist options
  • Save myfreeer/898f2e11378debdbddd7cfbf09d6ab43 to your computer and use it in GitHub Desktop.
Save myfreeer/898f2e11378debdbddd7cfbf09d6ab43 to your computer and use it in GitHub Desktop.
get selector from element
/**
* Is a selector returns only one result
* @param {String} selector - number of threads to run
* @return {Boolen} result
*/
const isUniqueSelector = (selector) => {
const result = document.querySelectorAll(selector);
if (result && result.length === 1)
return true;
return false;
};
/**
* Get index of children element in its parent element
* @param {Element} child - the child element
* @return {Number} index
*/
const getChildIndex = (child) =>
Array.prototype.indexOf.call(child.parentElement.children, child);
/**
* Get selector from an element
* @license BSD-3-Clause
* @param {Element} element - the element to get selector
* @return {String} the selector
*/
const getSelector = (element) => {
if (!(element && element instanceof Element))
throw new TypeError('getSelector: "element" is not an Element');
if (element.id && isUniqueSelector('#' + element.id))
return '#' + element.id;
let selector = element.tagName.toLowerCase();
if (element.className) {
selector = '.' + element.className.replace(/ /g, '.');
if (isUniqueSelector(selector))
return selector;
selector = element.tagName.toLowerCase() + selector;
if (isUniqueSelector(selector))
return selector;
}
if (element.parentElement) {
const index = getChildIndex(element);
if (index < 0)
throw new Error('findChildIndex failed');
return getSelector(element.parentElement) + '>' + selector + `:nth-child(${index + 1})`;
}
};
export default getSelector;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment