0

I want to get the exact location of an html element, and output the address of that element, the logic goes like this.

<div id="foo">
   <article>
       <div>
          <p>you found me</p>
       </div>
   </article>
<div>

So that is the sample html, now lets say the user click something on that mark up, in this case lets say the user click the 'p' tag. how do I write my JavaScript to output the address of that 'p' tag.

     function getAddress(){
         // code here
         console.log('the user click the ')
         console.log(address)
     }

Desired output:

      // Console
      log: the user click the
      log: #foo > article > div > p

2 Answers2

1

Something like this:

$(document).ready(function () {
    var path = '';
    $('#foo').on('click', '*', function (e) {
        path = $(this).prop("tagName");
        $(this).parents().each(function () {
            path = $(this).prop("tagName") + ' > ' + path;
        });
        alert(path);
        e.stopPropagation();
    });
})

Sample fiddle

UPDATE

To add the id attributes:

$(document).ready(function () {
    var path = '';
    $('#foo').on('click', '*', function (e) {
        path = $(this).prop("tagName").toLowerCase();
        $(this).parents().each(function () {
            let id = $(this).attr('id');
            path = $(this).prop("tagName").toLowerCase() + (typeof id != 'undefined' ? '#'+id : '') + ' > ' + path;
        });
        alert(path);
        e.stopPropagation();
    });
});

Updated fiddle

UPDATE on Uppercase Tag Names

Based on MDN

In XML (and XML-based languages such as XHTML), tagName preserves case. On HTML elements in DOM trees flagged as HTML documents, tagName returns the element name in the uppercase form. The value of tagName is the same as that of nodeName.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName

Frank Fajardo
  • 7,034
  • 1
  • 29
  • 47
-1

I am using jQuery and created this code snippet. Click on P tag

jQuery("p").click(function(){
  var parentEls = $(this).parents()
  .map(function() {
    return this.tagName;
  })
  .get()
  .join(">");
  alert(parentEls);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
   <article>
       <div>
          <p>you found me</p>
       </div>
   </article>
<div>
Sourabh Somani
  • 2,138
  • 1
  • 13
  • 27