Skip to content

Instantly share code, notes, and snippets.

@kdzwinel
Created December 8, 2017 00:24
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 kdzwinel/2e2f35af56d6da07fbfac12069bf5cff to your computer and use it in GitHub Desktop.
Save kdzwinel/2e2f35af56d6da07fbfac12069bf5cff to your computer and use it in GitHub Desktop.
Simple alternative to the axe-core getSelector
const commonNodes = [
'div', 'span', 'p',
'b', 'i', 'u', 'strong', 'em',
'h2', 'h3',
];
/**
* @param {Array<string>} attributes
* @returns {Map<string, string>}
*/
function getAttributeMap(attributes) {
const map = new Map();
for (let i=0; i<attributes.length; i+=2) {
const name = attributes[i].toLowerCase();
const value = attributes[i + 1].trim();
if (value) {
map.set(name, value);
}
}
return map;
}
/**
* @param {Node} node
* @returns {string}
*/
function getSelector(node) {
const selector = [];
let currentNode = node;
while (currentNode && currentNode.nodeName !== '#document') {
const attributeMap = getAttributeMap(currentNode.attributes);
const localeName = currentNode.localName.toLowerCase();
if (attributeMap.has('id')) {
selector.push('#' + attributeMap.get('id'));
} else if (!commonNodes.includes(localeName) || !attributeMap.has('class')) {
selector.push(localeName);
} else {
selector.push('.' + attributeMap.get('class').split(/\s+/).join('.'));
}
currentNode = currentNode.parentNode;
}
return selector.reverse().join(' > ');
}
@kdzwinel
Copy link
Author

kdzwinel commented Dec 8, 2017

screen shot 2017-12-08 at 01 22 29

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment