如何获得一个HTML元素

问题描述:

我想获得一个HTML元素的确切位置,并输出该元素的地址的准确位置,逻辑是这样的。如何获得一个HTML元素

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

所以这是样品HTML,现在可以说,用户点击该标记的东西,在这种情况下,可以说,用户点击“P”标签。如何编写我的JavaScript来输出该'p'标签的地址。

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

所需的输出:

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

什么背后的任何搜索算法的逻辑是什么?或者你想回溯到父母带有ID? – Omi

+0

@omi基本上我要回溯到父带有ID –

事情是这样的:

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

要添加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

UPDATE基于MDN

在XML(大写标签名称

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

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

+0

这正是我想要的,但为什么是字符串全部大写? –

+0

太感谢你了..先生... –

+0

@MarvenWilsonSDonque,看到我更新的答案,你对大写标签名称的问题。 –

我使用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>