Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quantuminformation/51820514b48b20a996e9 to your computer and use it in GitHub Desktop.
Save quantuminformation/51820514b48b20a996e9 to your computer and use it in GitHub Desktop.
Get unique query selector for element
/**
*
* @param e event from the DOM that we want to workout the testing path.
*/
getUniqueQueryPathToDomEventTarget: function (e) {
let hasEmberIdRegex = /ember[\d]+/;
if (e.target.id && !hasEmberIdRegex.test(e.target.id)) {
return "#" + e.target.id;
} else {
let path = e.path.reverse().slice(2); //remove the window and document path sections
let fullPath = path.map(function (element) {
// we need to make each path segment more specific if other siblings of the same type exist
let index = findNthChildIndex(element);
return element.localName + (index !== -1 ? ':nth-child(' + index + ')' : '');
}).join('>');//join all the segments for the query selector
console.log(fullPath);
return fullPath;
}
}
};
/**
* Gets the nth child index so we can select the element directly
*
* @param element
* @returns {number}
*/
function findNthChildIndex(element) {
let parent = element.parentNode;
if (!parent) {//its the <html> tag
return -1;
}
let children = parent.children;
let hasOthers = [].some.call(children, function (elem) {
return elem.tagName === element.tagName && elem !== element;
});
if (!hasOthers) {
return -1;
}
return Array.from(children).indexOf(element) + 1;//because nth child is 1 indexed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment