Get unique selector of element in Jquery
I'll answer this myself, because i found a solution which i had to modify. The following script is working and is based on a script of Blixt:
jQuery.fn.extend({ getPath: function () { var path, node = this; while (node.length) { var realNode = node[0], name = realNode.name; if (!name) break; name = name.toLowerCase(); var parent = node.parent(); var sameTagSiblings = parent.children(name); if (sameTagSiblings.length > 1) { var allSiblings = parent.children(); var index = allSiblings.index(realNode) + 1; if (index > 1) { name += ':nth-child(' + index + ')'; } } path = name + (path ? '>' + path : ''); node = parent; } return path; }});
Same solution like that one from @Alp but compatible with multiple jQuery elements.
jQuery('.some-selector')
can result in one or many DOM elements. @Alp's solution works unfortunately only with the first one. My solution concatenates all them with ,
.
If you want just handle the first element do it like this:
jQuery('.some-selector').first().getPath();// orjQuery('.some-selector:first').getPath();
Improved version
jQuery.fn.extend({ getPath: function() { var pathes = []; this.each(function(index, element) { var path, $node = jQuery(element); while ($node.length) { var realNode = $node.get(0), name = realNode.localName; if (!name) { break; } name = name.toLowerCase(); var parent = $node.parent(); var sameTagSiblings = parent.children(name); if (sameTagSiblings.length > 1) { var allSiblings = parent.children(); var index = allSiblings.index(realNode) + 1; if (index > 0) { name += ':nth-child(' + index + ')'; } } path = name + (path ? ' > ' + path : ''); $node = parent; } pathes.push(path); }); return pathes.join(','); }});
I think a better solution would be to generate a random id and then access an element based on that id:
Assigning unique id:
// or some other id-generating algorithm$(this).attr('id', new Date().getTime());
Selecting based on the unique id:
// getting unique idvar uniqueId = $(this).getUniqueId();// or you could just get the id:var uniqueId = $(this).attr('id');// selecting by id:var element = $('#' + uniqueId);// if you decide to use another attribute other than id:var element = $('[data-unique-id="' + uniqueId + '"]');