JSFiddle - React, Tailwind, and code Playground

by AndyE

HTML

<div>Current path: <code></code></div>
    <div>
            <div>
                Not selected
            </div>
        <span>Hello</span>
            <div>
                Selected Text
            </div>
        </div>

JavaScript

$(document).mouseover(function (evt) {
    // Get the ancestry of the elements
    var els = $(evt.target).parents().andSelf(),
        res = [];
    
    $.each(els, function () {
        var $this = $(this),
            index = "",
            sibs;
        
        // Get the index only if the element has siblings with the same tag name
        if ((sibs = $this.siblings(this.tagName).andSelf()).length > 1)
            index = "[" + sibs.index(this) + "]";
        
        // Append to the resuly array
        res.push(this.tagName + index);
    });
    
    // Join the array in XPath format
    res = "//" + res.join("/");
    
    $("code").text(res);
});