JQuery Find, Parents, and Siblings
$.parent() or $.parents(). The difference between the two is that the latter travels more than just a single level in the DOM. Obviously that makes it a bit less efficient but it is exhaustive. If you know you'll need to travel up a layer or two to find the parent element you're looking for then use parents. The example below demonstrates the button changing the parent row it is in.
$( "button" ).parents("tr").css("font-family", "Times New Roman" );
If you need to go down in the DOM you can use either $.children() or $.find(). Again the difference is that the latter travels more than one layer. An interesting thing that may happen is when you are at the level you want to be but need to find an element at that same level. That is where $.siblings() comes in. It will search for the element on the current level of the DOM you are in. Combining these methods together can help you locate elements all throughout your page. For example, once I needed to find the nearest error messages div because I had one near a variety of inputs and place text inside of it. I first used $.parents('error-row') to find the row it was in. Then used $.children('.error-display') to find the div within that held the text.
Obviously naming things uniquely with id's is the safest way to go as you can reference things directly but in the case of a complicated page with many layers and hidden elements it may be nice to traverse your page to find your elements. It also may be easier to simply change the nearest element rather than name every little item on your page. JQuery traversal has its place and remember if you can't find it at one level you may need to go up one more.
Comments
Join the discussionNo comments yet. Be the first to comment.




