Get CSS Selector Path Of An Element Using The jQuery getPath Plugin

Get CSS Selector Path Of An Element Using The jQuery getPath Plugin
File Size: 25.8 KB
Views Total: 56
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

getPath is a tiny jQuery plugin for developers that allows you to get the entire CSS selector path of the given DOM element within the document. It doesn't just cover unique IDs, but also tag names, pseudo-elements, etc.

See Also:

How to use it:

1. Download the plugin and include the jQueryGetPath.js after loading the latest jQuery library (slim build is recommended).

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/js/jQueryGetPath.js"></script>

2. Attach the function getPath() to the target element. That's it.

$(function(){
  jQuery(element).getPath(); 
});

3. A real world example.

<div id="example">
  <div class="well">
    <div class="pathfinder">Div without ID</div>
  </div>
  <div class="well">
    <div id="withId" class="pathfinder">Div with ID</div>
  </div>
</div>
(document).on({
  mouseenter: function () {
    var $currentNode = $(this);
    var cssPathForThisNode = $currentNode.getPath();
    $('#resultDiv').html(cssPathForThisNode);
  },
}, '.pathfinder');
// output:

Div without ID: [div="example"] > div:nth-child(1) > div

Div with ID: [div="withID"]

This awesome jQuery plugin is developed by arjshiv. For more Advanced Usages, please check the demo page or visit the official website.