Vivek Tankaria
Vivek Tankaria

Reputation: 1311

How to create a Xpath of the clicked element using Javascript or Jquery?

I have a webpage where I bind a click event on the element. When user clicks on the particular element. I want to get generate the XPath of the element starting from html or body tag. i.e "The Absolute Xpath"

Suppose in below html sample I click on span having text as "USA" so the Absolute Xpath would be

/html[1]/body[1]/div[2]/div[1]/div[1]/span[1]
<html>
    <body>
        <div class="header">Countries</div>
        <div class="row">
            <div class="row_in">
                <div class="row_in_in">
                    <span>India</span>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="row_in">
                <div class="row_in_in">
                    <span>USA</span>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="row_in">
                <div class="row_in_in">
                    <span>UK</span>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="row_in">
                <div class="row_in_in">
                    <span>France</span>
                </div>
            </div>
        </div>
    </body>
</html>

Do we have any library where it can help me generate the XPath where I pass the element Dom and it can generate it?

I came across few libraries but that help detect the Content inside the html based on provided Xpath.

Upvotes: 2

Views: 1907

Answers (1)

Mohammad
Mohammad

Reputation: 21489

You need to loop through clicked element and it parents to do this work. So you can call a function nesting to do this work.

var xpath;
$("*").click(function(e){
  xpath = '';
  addXpath($(this));
  console.log(xpath);
  e.stopPropagation();
});

function addXpath($ele){
  var tagName = $ele[0].tagName.toLowerCase();
  var index = $ele.parent().children(tagName).index($ele)+1;
  xpath = '/'+tagName +'['+index+']'+ xpath;
  !$ele.parent().is(document) ? addXpath($ele.parent()) : "";
}
body {background: green}
.header {background: orange}
.row_in {background: yellow}
.row_in_in {background: blue}
span {background: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">Countries</div>
<div class="row">
<div class="row_in">
  <div class="row_in_in">
    <span>India</span>
  </div>
</div>
</div>
<div class="row">
<div class="row_in">
  <div class="row_in_in">
    <span>USA</span>
  </div>
</div>
</div>
<div class="row">
<div class="row_in">
  <div class="row_in_in">
    <span>UK</span>
  </div>
</div>
</div>
<div class="row">
<div class="row_in">
  <div class="row_in_in">
    <span>France</span>
  </div>
</div>
</div>

Upvotes: 2

Related Questions