We can use JavaScript to get parent element or jQuery to get parent element but which one would be best for you is up to your need and familiarity with JavaScript and jQuery. In this article we will take different conditions and examples to show how jquery finds parent element and same case with JavaScript.
First we will see the simplest form of parent of any element
<div id="div1"> <div id="div2"> <input type="button" id="btn1" value="button1" /> </div> <input type="button" id="btn2" value="button2" /> </div>So in this case for button1 parent is div2 while for button2 parent is div1 so how to get them by using jquery or JavaScript
// By using JavaScript document.getElementById("btn1").parentNode; // result: div2 document.getElementById("btn2").parentNode; // result: div1 // By using jQuery $("#btn1").parent();// result: div2 $("#btn2").parent();// result: div1Now we will see a complicated case and will try to get parent element by using jQuery and JavaScript, suppose we have following HTML
We already discussed how to get first parent but we don’t know how to get the first parent of a particular element type, say we want to get the first parent of type tr for both the button bbuttontn1 and button2, its really easy see this
$(this).parents('tr:first'); // result: tr element OR $(this).closest('tr'); // result: tr elementWhat will happen if we will use div in place of tr, like this
$(this).parents('div:first'); OR $(this).closest('div');Any guess? button1 will get his parent as outerDiv while button2 will get his parent as innerDiv.
jQuery nth parent : How to get the nth parent of any element? We can use parents().eq(N) to get nth parent of any element, so see to get first, second, third ….. parent of button2 we can use
jQuery parent with a particular id or name: Suppose we want to get parent having id “outerDiv” for button2 then
$(this).parents('#outerDiv'); OR $(this).parents('#outerDiv');As you can notice in most cases we have not used classic JavaScript because those are quite complicated, we would need to use parentNode.parentnode .....and check every time is this the correct parent which I need so I will suggest to use jQuery in place of classic JavaScript because it is easy and handy to read, write and remember.
| Process manager with a reputed organization, Fond of learning new features and technology related to C#, ASP.Net, SQL Server, MVC etc.I like to help others, if I can |
By Hamden On 06 Apr, 13 Viewed: 10,236 |
The following code shows how to select parent with parent selector $("td:parent").
<html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){<!-- w w w . ja v a 2 s.co m--> $("td:parent").fadeTo(1500, 0.3); }); </script> </head> <body> <table border="1"> <tr><td>Value 1</td><td></td></tr> <tr><td>Value 2</td><td></td></tr> </table> </body> </html>
The code above generates the following result.