Skip to content

Instantly share code, notes, and snippets.

@jeromepl
Last active September 18, 2017 23:35
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 jeromepl/e77469ebf862494387bdfbaca7a9a57d to your computer and use it in GitHub Desktop.
Save jeromepl/e77469ebf862494387bdfbaca7a9a57d to your computer and use it in GitHub Desktop.
Get a CSS-style query to a DOM element. (With JQuery)
// 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));
// 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