Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to get to a particular child of a parent?

To give a simplified example, I've got the following block repeated on the page lots of times (it's dynamically generated):

<div class="box">    <div class="something1"></div>    <div class="something2">       <a class="mylink">My link</a>    </div> </div> 

When clicked, I can get to the parent of the link with:

$(".mylink").click(function() {    $(this).parents(".box").fadeOut("fast"); }); 

However... I need to get to the <div class="something1"> of that particular parent.

Basically, can someone tell me how to refer to a higher-level sibling without being able to refer to it directly? Let's call it big brother. A direct reference to the big brother's class name would cause every instance of that element on the page to fade out - which is not the desired effect.

I've tried:

parents(".box .something1") ... no luck. parents(".box > .something1") ... no luck. siblings() ... no luck. 

Anyone? Thanks.

like image 795
Tom Avatar asked Mar 08 '10 02:03

Tom


People also ask

Can we get the children element from the parent element using jQuery?

jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.

How do I find a specific parent in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.


2 Answers

Calling .parents(".box .something1") will return all parent elements that match the selector .box .something. In other words, it will return parent elements that are .something1 and are inside of .box.

You need to get the children of the closest parent, like this:

$(this).closest('.box').children('.something1') 

This code calls .closest to get the innermost parent matching a selector, then calls .children on that parent element to find the uncle you're looking for.

like image 65
SLaks Avatar answered Sep 28 '22 10:09

SLaks


$(this).parent() 

Tree traversal is fun

$(this).parent().siblings(".something1");  $(this).parent().prev(); // if you always want the parent's previous sibling  $(this).parents(".box").children(".something1"); 

And much more ways, you might find these docs helpful.

like image 35
Anurag Avatar answered Sep 28 '22 10:09

Anurag