Reputation: 129
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
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
Reputation: 417
This should get the job done :
var parentClass = $('#childElement').parent().attr('class');
Upvotes: 1
Reputation: 57
Try this..... $(this).parent().attr('class');
...m sure this will work :)
Upvotes: 1
Reputation: 20313
Use .attr()
Try:
$(document).ready(function(){
$(".link").click(function(){
var div=$(this).parent().attr('class');
alert(div);
});
});
Upvotes: 1
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