Skip to content

Instantly share code, notes, and snippets.

@luislobo14rap
Last active January 30, 2021 22:30
Show Gist options
  • Save luislobo14rap/90e4e2dee6bdce547428c76e3f2db7e4 to your computer and use it in GitHub Desktop.
Save luislobo14rap/90e4e2dee6bdce547428c76e3f2db7e4 to your computer and use it in GitHub Desktop.
getFullPath.js
// getFullPath.js v1.0.4
function getFullPath($element) { // jquery
if (typeof $element.jquery == 'undefined') {
$element = $($element);
};
let path = [];
// pause if $element is HTML
let thisIsHtml = false;
while (thisIsHtml == false) {
let tagName = $element.prop('tagName').toLowerCase();
if (tagName == 'html') {
thisIsHtml = true;
};
let elementInfos = {
attrs: getAttrs($element, tagName),
class_: getClasses($element),
id: getId($element),
tagName: tagName
};
path.unshift(tagName == 'html' ? '' : ' ', elementInfos.tagName + elementInfos.id + elementInfos.class_ + elementInfos.attrs);
$element = $element.parent();
};
return path.join('');
};
function getClasses($element) {
let class_ = $element.attr('class') || '';
if (class_.length > 0) {
class_ = '.' + class_.replace(/(^\s+|\s+$)/g, '').replace(/\s+/g, '.');
};
return class_;
};
function getId($element) {
let id = $element.attr('id') || '';
if (id.length > 0) {
id = '#' + id;
};
return id;
};
function getAttrs($element, tagName) {
let attrs = '';
let attrs_ = $element[0].outerHTML;
for (i = 0; i < attrs_.length; i++) {
if (attrs_[i] != '>') {
attrs += attrs_[i];
} else {
break;
};
};
attrs = attrs.substring(1).replace(tagName, '').trim();
attrs = attrs.replace(/\=(\"\"|\".+?\")/g, '').split(' ');
// remove class and id attrs, if exists and add [ and ] brackets
newAttrs = [];
for (let i = 0; i < attrs.length; i++) {
if (attrs[i] != 'class' && attrs[i] != 'id') {
newAttrs.push('[' + attrs[i] + ']');
};
};
attrs = newAttrs.join('');
if (attrs == '[]') {
attrs = '';
};
return attrs;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment