Last active
September 18, 2017 23:35
-
-
Save jeromepl/e77469ebf862494387bdfbaca7a9a57d to your computer and use it in GitHub Desktop.
Get a CSS-style query to a DOM element. (With JQuery)
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
// Same as the other file, but this time as a JQuery plugin. | |
// Usage: $(someElement).getQuery(); | |
(function ($) { | |
$.fn.getQuery = function() { | |
var id = this.attr('id'); | |
var localName = this.prop('localName'); | |
if (id) | |
return '#' + escapeCSSString(id); | |
if (localName === 'html') | |
return 'html'; | |
var parentSelector = this.parent().getQuery(); | |
var index = this.index(parentSelector + '>' + localName) + 1; | |
return parentSelector + '>' + localName + ':nth-of-type(' + index + ')'; | |
}; | |
// Colons and spaces are accepted in IDs in HTML but not in CSS syntax | |
// Similar (but much more simplified) to the CSS.escape() working draft | |
function escapeCSSString(cssString) { | |
return cssString.replace(/(:)/g, "\\$1"); | |
} | |
}(jQuery)); |
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
// From an DOM element, get a query to that DOM element | |
// Returns, for example, "html>body:nth-of-type(1)>div:nth-of-type(2)>div:nth-of-type(2)>div:nth-of-type(1)" | |
// Or, "#some-id>div:nth-of-type(2)" | |
function getQuery(element) { | |
if (element.id) | |
return '#' + escapeCSSString(element.id); | |
if (element.localName === 'html') | |
return 'html'; | |
var parent = element.parentNode; | |
var jEl = $(element); // Requires JQuery | |
var parentSelector = getQuery(parent); | |
var index = jEl.index(parentSelector + '>' + element.localName) + 1; | |
return parentSelector + '>' + element.localName + ':nth-of-type(' + index + ')'; | |
} | |
// Colons and spaces are accepted in IDs in HTML but not in CSS syntax | |
// Similar (but much more simplified) to the CSS.escape() working draft | |
function escapeCSSString(cssString) { | |
return cssString.replace(/(:)/g, "\\$1"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment