Skip to content

Instantly share code, notes, and snippets.

@k08045kk
Last active February 11, 2023 12:13
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 k08045kk/d239bec86ae9b06c438e7e2bf67575fb to your computer and use it in GitHub Desktop.
Save k08045kk/d239bec86ae9b06c438e7e2bf67575fb to your computer and use it in GitHub Desktop.
Element から CSS Selector を取得する
/**
* Element から CSS Selector を取得する
* @author toshi (https://github.com/k08045kk)
* @license MIT License | https://opensource.org/licenses/MIT
* @version 1
* @since 1 - 20230211 - 初版
* @see https://www.bugbugnow.net/2023/02/get-css-selector.html
* @see https://gist.github.com/k08045kk/d239bec86ae9b06c438e7e2bf67575fb
* @param {Element} element - 要素
* @return {string} - CSS Selector
*/
var getCSSSelector = function(element) {
if (!(element && element instanceof Node)
|| !(element.nodeType === Node.ELEMENT_NODE || (element=element.parentElement))) {
return 'unknown';
}
var array = [];
for (; element; element=element.parentElement) {
if (element.id) {
// #id
array.unshift('#'+element.id)
break;
} else {
// tagName.className:nth-of-type(n)
var tagName = element.tagName;
var text = tagName.toLowerCase();
var list = element.classList;
var len = list.length;
for (var i=0; i<len; i++) { text += '.'+list[i]; }
var n = 0;
for (var pre=element; (pre=pre.previousElementSibling) && (pre.tagName != tagName || ++n); ) {}
var nth = n+1;
if (!n) {
for (var next=element; (next=next.nextElementSibling) && (next.tagName != tagName || !++n); ) {}
}
if (n) {
text += ':nth-of-type('+nth+')';
}
array.unshift(text);
}
}
return array.join(' > ');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment