0

I have hold of an "A" tag, and I would like to know what classes it's parents have got...so:

<div class="topone">
    <div class="middleone">
        <a href="#" class="thisone">tag</a>
    </div>
</div>

So I've got "thisone", but I want to know if there is a div above it somewhere that has the class of "topone"

...no jquery though, can't use jquery for this

Paul
  • 9,409
  • 13
  • 64
  • 113

4 Answers4

4

You can use the .className property to access an element's class and .parentNode to go to the parent element.

var classes = [];
for(var el = document.getElementById('#yourlink'); el; el = el.parentNode) {
    classes.push(el.className);
}

Note that classes[0] contains the classes of the element itself - but I'm sure it's no problem for you to modify the code accordingly if you do not want that.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

You can use .parentNode and className properties.

This is the way:

document.getElementById("MyElement").className

Fiddler Demo

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
0

You can write something like this

give your a tag an id, say bottomone

var e = document.getElementById("bottomone").parentNode.className will give you the class name as middle one.

and for the upper div, you can write

var e = document.getElementById("bottomone").parentNode.parentNode.className
nmc
  • 8,724
  • 5
  • 36
  • 68
user1651198
  • 31
  • 2
  • 7
0
var element =document.getElementById("topone");      
var liArray = element.childNodes;
      var i=0, item;
    if(element != null)
    {var status=0;
      while (item = liArray[i++]) {
        if (item.nodeType == 1) {
         if(item.className=="thisone"){status=1;}
        }
      }
    if(status==1){alert('it have parent node');}else{alert('it doen`t have parent node');}
    }else{alert('it doesn`t have parent node');}

i have tried at my level as per your requirement may it help you