如何获取html元素的确切位置

时间:2017-07-18 23:15:42

标签: javascript jquery html

我想获得html元素的确切位置,并输出该元素的地址,逻辑就像这样。

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

这就是示例html,现在让我们说用户点击该标记上的内容,在这种情况下,让我们说用户点击“&#39; p&#39;标签。如何编写我的JavaScript来输出那个&#39; p&#39;标签

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

期望的输出:

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

2 个答案:

答案 0 :(得分:1)

这样的事情:

$(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

<强>更新

添加id属性:

$(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

更新大写标记名称

基于MDN

  

在XML(以及基于XML的语言,如XHTML)中,tagName保留了大小写。在标记为HTML文档的DOM树中的HTML元素上,tagName以大写形式返回元素名称。 tagName的值与nodeName的值相同。

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

答案 1 :(得分:-1)

我正在使用jQuery并创建了此代码段。点击 P标记

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>

相关问题