jQuery: How to get to a particular child of a pare

2019-01-12 21:53发布

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.

5条回答
放荡不羁爱自由
2楼-- · 2019-01-12 22:38
$(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.

查看更多
We Are One
3楼-- · 2019-01-12 22:48

This will find the first parent with class box then find the first child class with regex matching something and get the id.

$(".mylink").closest(".box").find('[class*="something"]').first().attr("id")
查看更多
干净又极端
4楼-- · 2019-01-12 22:50

If I understood your problem correctly, $(this).parents('.box').children('.something1') Is this what you are looking for?

查看更多
一夜七次
5楼-- · 2019-01-12 22:52

You could use .each() with .children() and a selector within the parenthesis:

//Grab Each Instance of Box.
$(".box").each(function(i){

    //For Each Instance, grab a child called .something1. Fade It Out.
    $(this).children(".something1").fadeOut();
});
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-12 22:57

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.

查看更多
登录 后发表回答