How can I get the class name of the parent div from which a html link calls a javascript function?
In the following code example:
<div class="parent-class">
<a href="javascript:parent(this.parent)">Find parent</a>
</div>
<script>
function parent(parent) {
var theValueImLookingFor = (parent.className);
}
</script>
I would like the "theValueImLookingFor" to be "parent-class", but I keep getting "undefined".
I been trying to figure this out for almost an hour, what can I change to make this work? I understand there are more static ways to get this information, but for my specific purpose I really need to identify the div through the javascript function from which it is called.
How can I get the class name of the parent div from which a html link calls a javascript function?
In the following code example:
<div class="parent-class">
<a href="javascript:parent(this.parent)">Find parent</a>
</div>
<script>
function parent(parent) {
var theValueImLookingFor = (parent.className);
}
</script>
I would like the "theValueImLookingFor" to be "parent-class", but I keep getting "undefined".
I been trying to figure this out for almost an hour, what can I change to make this work? I understand there are more static ways to get this information, but for my specific purpose I really need to identify the div through the javascript function from which it is called.
Share Improve this question asked Oct 17, 2015 at 0:09 SVisscherSVisscher 231 gold badge1 silver badge3 bronze badges2 Answers
Reset to default 3You've tagged this with jQuery, which will be the easiest way to find the details of the parent div. Something like
<div class="parent-div">
<a id="link">Find Parent</a>
</div>
<script>
$('#link').click(function() {
alert($(this).parent().attr('class'));
});
</script>
I would avoid using JavaScript as an href value, and do something like this:
var pre = onload;
onload = function(){
if(pre)pre();
var doc = document;
function getParentClassName(childNode){
return childNode.parentNode.className;
}
console.log(getParentClassName(doc.getElementsByTagName('a')[0]));
}