Search code examples
javascripthtmlinnerhtmltagname

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".

<div id="ey">
<ul>
<li>
  <a href="korstone.htm">Home</a>
</li>
</ul>

<ul>
<li>
  <a href="#">About us</a>
</li>
</ul>
</div>

Solution

  • lets' say you start with by passing the 'a' element t a function onclick.

    <a onclick='findWhereIAm(this)'>blah blah</a>
    

    You then can find out what it's in by using the parentNode property. 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.
    }
    
     }