Created
September 9, 2010 13:43
-
-
Save 3rd-Eden/571870 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
elementToCSS3 = function( e ){ | |
// optimized for id lookups | |
if( e.id ){ return { selector:"#" + e.id, index:0 }; } | |
var nodeName = e.nodeName.toLowerCase(), | |
css3 = { selector: nodeName + ( e.className ? "." + e.className.split(" ").join(".") : ""), index:0 }, | |
node = e; | |
// speedup for parent lookups | |
var parent = node.parentNode; | |
var samekind = parent.getElementsByTagName( nodeName ); | |
// search for the :nth-child | |
for( var i = 0; i < samekind.length; i++ ){ | |
if( samekind[i] == node ){ | |
css3.index = i; | |
break; | |
} | |
} | |
// create a loopup chain | |
while( node.parentNode && node.parentNode !== document.documentElement ){ | |
parent = node.parentNode; | |
// again, optimize for id's | |
if( parent.id ){ | |
css3.selector = "#" + parent.id + " " + css3.selector; | |
return css3; | |
} | |
css3.selector = parent.nodeName.toLowerCase() + ( parent.className ? "." + parent.className.split(" ").join(".") : "" ) + " " + css3.selector; | |
node = parent; | |
} | |
return css3; | |
}; | |
// returns { selector: "css3 selector", index: "the index of result array where the item is"} |
This file contains hidden or 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
document.body.onclick = function( e ){ | |
var element = e.target; | |
var css3 = elementToCSS3( element ); | |
var qsa = document.querySelectorAll( css3.selector ); | |
console.info( css3 ); | |
console.log( qsa ); | |
console.log( element ); | |
console.log( element == qsa[css3.index] ); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment