- SPLessons

jQuery – parent element id or class

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

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


      <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>

Step1 :

I will give you simple example how to use it. Add below code in HTML body


<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>

Step2 :

Add below code in page header 

<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>

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.