[英]JavaScript : Getting Tag name of a certain innerHtml text
I will really appreciate you if you can help me with the following problem. 如果您可以解决以下问题,我将非常感谢您。 Suppose that I know the "Home" text but now I want to catch where is it in. Means is it in the div tag or in a level tag .Here you should help me to find the div tag and it's id "ey". 假设我知道“ Home”文本,但是现在我想知道它在哪里。是指它在div标签中还是在level标签中。在这里您应该帮助我找到div标签,并且它的ID为“ ey”。
<div id="ey">
<ul>
<li>
<a href="korstone.htm">Home</a>
</li>
</ul>
<ul>
<li>
<a href="#">About us</a>
</li>
</ul>
</div>
lets' say you start with by passing the 'a' element ta function onclick. 假设您通过传递a元素ta函数onclick开始。
<a onclick='findWhereIAm(this)'>blah blah</a>
You then can find out what it's in by using the parentNode property. 然后,您可以使用parentNode属性来找出其中的内容。 And you can travel up the chain of parents by using a loop. 而且,您可以使用循环,沿父母链向上移动。
function findWhereIAm(element){
var parent=element.parentNode;
while(parent.nodeName!="BODY"){
if(parent.id=='whatever value you are checking'){
//do your stuff
alert(parent.id);
//break or you'll keep looping through
break;
}
parent=parent.parentNode.
}
}
EDIT 编辑
var as=document.getElementsByTagName('a');
var element;
for(var i=0;i<as.length;i++){
if(as[i].innerHTML=='Home'){
element=as[i];
break;
}
}
if(element){
var parent=element.parentNode;
while(parent.nodeName!="BODY"){
if(parent.id=='whatever value you are checking'){
//do your stuff
alert(parent.id);
//break or you'll keep looping through
break;
}
parent=parent.parentNode.
}
}
The following will tell you the ID: 以下内容将告诉您ID:
$("*:contains('Home')").closest("div").prop("id")
This will tell you the tag name 这将告诉您标签名称
$("*:contains('Home')").closest("div").prop("tagName")
try this 尝试这个
<a onclick='search(this)'>home</a>
function serach(el){
var a = el.parent('#ey');
console.log(a)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.