Skip to content

Instantly share code, notes, and snippets.

@dsturley
Created April 10, 2014 17:55
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 dsturley/77cc547ad95ced341dbe to your computer and use it in GitHub Desktop.
Save dsturley/77cc547ad95ced341dbe to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<title>getQuerySelector Bug</title>
<script>
var axs = {};
axs.browserUtils = {};
axs.browserUtils.matchSelector = function(element, selector) {
if (element.webkitMatchesSelector)
return element.webkitMatchesSelector(selector);
if (element.mozMatchesSelector)
return element.mozMatchesSelector(selector);
return false;
}
axs.utils = {};
axs.utils.getQuerySelectorText = function(obj) {
if (obj == null || obj.tagName == 'HTML') {
return 'html';
} else if (obj.tagName == 'BODY') {
return 'body';
}
if (obj.hasAttribute) {
if (obj.id) {
return '#' + obj.id;
}
if (obj.className) {
var selector = '';
for (var i = 0; i < obj.classList.length; i++)
selector += '.' + obj.classList[i];
var total = 0;
if (obj.parentNode) {
for (i = 0; i < obj.parentNode.children.length; i++) {
var similar = obj.parentNode.children[i];
if (axs.browserUtils.matchSelector(similar, selector))
total++;
if (similar === obj)
break;
}
} else {
total = 1;
}
if (total == 1) {
return axs.utils.getQuerySelectorText(obj.parentNode) +
' > ' + selector;
} else {
return axs.utils.getQuerySelectorText(obj.parentNode) +
' > ' + selector + ':nth-of-type(' + total + ')';
}
}
if (obj.parentNode) {
var similarTags = obj.parentNode.children;
var total = 1;
var i = 0;
while (similarTags[i] !== obj) {
if (similarTags[i].tagName == obj.tagName) {
total++;
}
i++;
}
var next = '';
if (obj.parentNode.tagName != 'BODY') {
next = axs.utils.getQuerySelectorText(obj.parentNode) +
' > ';
}
if (total == 1) {
return next +
obj.tagName;
} else {
return next +
obj.tagName +
':nth-of-type(' + total + ')';
}
}
} else if (obj.selectorText) {
return obj.selectorText;
}
return '';
};
</script>
</head>
<body>
<ul>
<li>One</li>
<li class="thing">Two</li>
<li class="thing">Three</li>
</ul>
<script>
var lastLi = document.querySelectorAll('.thing')[1];
var selector = axs.utils.getQuerySelectorText(lastLi);
console.assert(lastLi === document.querySelector(selector), 'nth-of-type means nth of same nodeName');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment