Created
December 8, 2017 00:24
-
-
Save kdzwinel/2e2f35af56d6da07fbfac12069bf5cff to your computer and use it in GitHub Desktop.
Simple alternative to the axe-core getSelector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(' > '); | |
} |
Author
kdzwinel
commented
Dec 8, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment