简体   繁体   中英

jQuery - get element inside parent div's friend div

HTML

 <div class="container-fluid"> <div class="input-page">...</div> <!-- field 1 --> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <!-- field 2 --> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <!-- field 3 --> <div class="col-md-12 col-sm-12 col-xs-12 no-padding"> <!-- I want to grab this block --> <div class="x_panel"> <div class="x_content"> <form class="data-table"> <div class="row">...</div> <div class="row">...</div> <div class="col-md-12 col-sm-12 col-xs-12 no-padding"> <div class="btn-group"> <button>Add</button> <!-- when I click this button --> <button>Other</button> </div> </div> </div> 

The above code is a simplified version, but with the actual code it looks like this: 在此处输入图片说明

Each " field " is a combination of the content div and the buttons div . When I press that Add button, I want to grab the content div that is right above it.

I was thinking about first trying $(this).closest('.container-fluid') , and then navigate to the div that is right above the div that has the button I clicked. But I don't know how. Any ideas?

One crude way would be to get the parent/parent's closest sibling with prev

 $("#AddButton").click(function() { var blockToGrab = $(this).parent().parent().prev(); // do stuff with block console.log("I found: " + blockToGrab.html()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container-fluid"> <div class="input-page">...</div> <!-- field 1 --> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <!-- field 2 --> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <!-- field 3 --> <div class="col-md-12 col-sm-12 col-xs-12 no-padding"> <!-- I want to grab this block --> <div class="x_panel"> <div class="x_content"> <form class="data-table"> <div class="row">...</div> <div class="row">...</div> </form> </div> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12 no-padding"> <div class="btn-group"> <button id="AddButton">Add</button> <!-- when I click this button --> <button>Other</button> </div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM