jQuery – parent element id or class
jQuery - parent element id or class
Description :
How to get Parent element Class or ID
Step1 :
Use below codes to get parent elements class or id in different ways
[javascript]
<script type="text/javascript" >
var Parent_ID = $('element').parent().attr('id'); // to get the ID of parent element
var Parent_class = $('element').parent().attr('class'); // to get the class of parent element
</script>
[/javascript]
Step1 :
I will give you simple example how to use it. Add below code in HTML body
[html]
<div id="Parent_Parent_Div">
<p id="parent_tag">
<input type="text" class="child_class" id="child_id">
</p>
<button id="btn">Click</button>
</div>
[/html]
Step2 :
Add below code in page header
[javascript]
<script type="text/javascript">
$(document).ready(function() {
// when click on #btn-
$('#btn').click(function(){
// get ID of parentt of ".child_class"
var idpr = $('.child_class').parent().attr('id'); // if you want class of that parent element just replace with 'id' with 'class'
alert('ID of the parent of the Input is:\n'+ idpr);
var idprofpr = $('.child_class').parent().parent().attr('id');
alert('ID of the parent of the Input is:\n'+ idprofpr);
});
});
</script>
[/javascript]
Now you can able to get the parent elements id and class, If you have any doubt to know more about this just add your comment below.