Skip to content

Instantly share code, notes, and snippets.

@tinganho
Created July 19, 2012 12:31
Show Gist options
  • Save tinganho/3143524 to your computer and use it in GitHub Desktop.
Save tinganho/3143524 to your computer and use it in GitHub Desktop.
CSS Selector specificity
function sortPoints(points) {
points.sort(function(a, b) {
if(a[0] > b[0])
return -1;
if(a[0] < b[0])
return 1;
if(a[1] > b[1])
return -1;
if(a[1] < b[1])
return 1;
if(a[2] > b[2])
return -1;
if(a[2] < b[2])
return 1;
else
return 0;
})
return points;
}
function specificity(selector, element) {
function is(selector, element) {
var div = document.createElement("div"),
matchesSelector = div.webkitMatchesSelector;
return typeof selector == "string" ? matchesSelector.call(element, selector) : selector === element;
}
function getBiggestPoint(points) {
var points = sortPoints(points);
return points[0];
}
var splittedSelector = selector.split(',');
var points = [];
for(var i in splittedSelector) if (splittedSelector.hasOwnProperty(i)) {
function numMatches(selector, regex) {
return (selector.match(regex)||[]).length;
}
if(!is(splittedSelector[i], element)) continue;
var numClasses = numMatches(splittedSelector[i], /\.[\w-_]+\b/g);
var numIds = numMatches(splittedSelector[i], /#[\w-_]+\b/g);
var numNamesInBraces = 0;
var namesInBraces = splittedSelector[i].match(/\[[^\]]*\b[\w-_]+\b[^\]]*\]/g) || [];
for (var idx = 0; idx < namesInBraces.length; ++idx) {
numNamesInBraces += (namesInBraces[idx].match(/\b[\w-_]+\b/g)||[]).length;
}
var results = [0,0,0];
results[0] = numIds;
results[1] = numMatches(splittedSelector[i], /\[[^\]]+\]/g) + numClasses;
results[2] = numMatches(splittedSelector[i], /\b[\w-_]+\b/g) - numIds - numClasses - numNamesInBraces;
points.push(results);
}
return getBiggestPoint(points);
}
var element = document.createElement('div');
element.className = 'hello juoo';
document.write(JSON.stringify(specificity("", element)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment