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

后端 未结 5 380
迷失自我
迷失自我 2020-12-04 09:23

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

&l
相关标签:
5条回答
  • 2020-12-04 09:55

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

    0 讨论(0)
  • 2020-12-04 10:01

    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.

    0 讨论(0)
  • 2020-12-04 10:05
    $(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.

    0 讨论(0)
  • 2020-12-04 10:05

    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")
    
    0 讨论(0)
  • 2020-12-04 10:22

    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();
    });
    
    0 讨论(0)
提交回复
热议问题