caesar
caesar

Reputation: 129

get the class of the parent html element

Hi guys I'm trying to get the class of the parent element of the element that I clicked

Ex:

<div class="mydiv"><a href="#" class="link">Click me</a></div> 

I want to get the class of the parent div(mydiv)

I tried this but it didn't work:

$(document).ready(function(){
$(".link").click(function(){
var div=$(this).parent().className;
alert(div);
});
});

it always gives me (undefined). any one can help?

Upvotes: 1

Views: 2157

Answers (6)

Ben Jackson
Ben Jackson

Reputation: 11922

className is a property of HTML Elements, not jQuery objects such as would be given by $(this).parent(). You can use:

$(this).parent()[0].className;

which accesses the DOM object representing the object ($(this).parent()[0]) and then looks up the className property.

Note that if you have multiple classes applied to an element then the className property will return a string consisting of all the class names separated spaces.

https://developer.mozilla.org/en-US/docs/Web/API/element.className

On newer browsers, you can use the classList property, which makes dealing with classes easier:

https://developer.mozilla.org/en-US/docs/Web/API/element.classList

Upvotes: 1

Thomas
Thomas

Reputation: 417

This should get the job done :

var parentClass = $('#childElement').parent().attr('class');

Upvotes: 1

Vishal Chawla
Vishal Chawla

Reputation: 57

Try this..... $(this).parent().attr('class'); ...m sure this will work :)

Upvotes: 1

Kiran
Kiran

Reputation: 20313

Use .attr() Try:

$(document).ready(function(){
$(".link").click(function(){
var div=$(this).parent().attr('class');
alert(div);
});
});

Upvotes: 1

PSL
PSL

Reputation: 123739

.parent() gives jquery object and className is a property of DOM element so try:

var div=$(this).parent()[0].className; // use [0] to get the DOM element and get the property

or

var div= $(this).parent().attr("class"); //Use jquery attr to get the value of the attribute class

Upvotes: 5

l2aelba
l2aelba

Reputation: 22147

Use .attr() {link}

$('.element').attr('class'); // Get class(es)
$('.element').attr('id'); // Get the ID

Upvotes: 1

Related Questions