Paul
Paul

Reputation: 9541

How do I find the classes assigned to an element in javascript (without jQuery)

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

Upvotes: 0

Views: 273

Answers (4)

user1651198
user1651198

Reputation: 31

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

Upvotes: 0

Gyan Chandra Srivastava
Gyan Chandra Srivastava

Reputation: 1380

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

Upvotes: 0

Vishal Suthar
Vishal Suthar

Reputation: 17194

You can use .parentNode and className properties.

This is the way:

document.getElementById("MyElement").className

Fiddler Demo

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318518

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.

Upvotes: 4

Related Questions