Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.