"When a jQuery button is clicked, retrieve the div element with a specific class

I'm currently in the midst of crafting a jQuery client script and my goal is to ensure it's adaptable to any situation.

One specific challenge I am facing is how to target a div with the class ".targets" when a button is clicked.

The structure of my markup is somewhat like this:

<form>
    <div class="products">
        <div class="container">
            <div class="form-group">
                <div class="col-md-12">
                    <button type="button" class="btn-add">Add</button>
                </div>
            </div>
            <div class="targets">
                ...
            </div>
        </div>
    </div>
    <div class="resources">
        <div class="container">
            <br/>
            <div class="form-group">
                <button type="button" class="btn-add">Add</button>
            </div>
            <br/>
            <div class="targets">
                ...
            </div>
        </div>
    </div>
</form>

This is the jQuery code I have so far:

$("form").on("click", "btn-add", function(e){
   var targets = $(this).closest(".container").find(".targets");
});

Although this solution works for now, I am concerned about potential changes in the markup.

Is there a way in jQuery to dynamically select the closest div with the class ".targets" on button click?

Appreciate your help :)

Answer №1

For selecting the closest element with the class container, you can use the following code:

(this).closest(".container").find(".targets");

This code snippet will identify the nearest element with the class container and then search for an element within it that has the class targets.

$("form").on("click", ".btn-add", function(e){
   var targets = $(this).closest(".container").find(".targets");
   console.log($(targets).text().trim())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <!-- Products section -->
    <div class="products">
        <div class="container">
            <div class="form-group">
                <div class="col-md-12">
                    <button type="button" class="btn-add">Add</button>
                </div>
            </div>
            <div class="targets">
                target1
            </div>
        </div>
    </div>
    <!-- Resources section, slightly different markup -->
    <div class="resources">
        <div class="container">
            <br/>
            <div class="form-group">
                <button type="button" class="btn-add">Add</button>
            </div>
            <br/>
            <div class="targets">
                target2
            </div>
        </div>
    </div>
</form>

Answer №2

Assuming the elements you are targeting will consistently be located inside the .products container, here is a potential solution:

$(this).closest('.products').find('.targets');

For more information on jQuery traversing methods, check out this helpful guide: http://api.jquery.com/category/traversing/

Answer №3

Give this a shot:

$(this).closest('.wrapper').find('.destinations')

Answer №4

One option is to utilize the closest() method, which looks for a selector higher up in the tree, and the find() method, which searches for a selector going down the tree

$(this).closest('.container').find('.targets')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Eradicate white space in a JavaScript code

Calling all JS programmers! Here's a challenge for you, check out this demo: https://codepen.io/gschier/pen/jkivt I'm looking to tweak 'The pen is simple.' to be 'The pen issimple.' by removing the extra space after 'is& ...

Encountering an issue while creating a controller in AdonisJS5

Whenever I attempt to execute the command node ace make:controller User an error is shown as follows Cannot locate module './commands/Make\Controller' Require stack: /Users/abiliocoelho/Desktop/socket/node_modules/@adonisjs/assembler/buil ...

Having difficulty retrieving the scope variable within the $watch function

While working on my AngularJS filter, I encountered an issue with accessing the scope object in a specific area. After making some code changes, the problem was resolved, but I am unsure of what caused it. It seems like my understanding of scope and direct ...

How can I only replace every second occurrence in a JS string?

Looking for help with JavaScript: "a a a a".replace(/(^|\s)a(\s|$)/g, '$1') I thought the result would be '', but it's showing 'a a' instead. Can someone explain what I'm missing? To clarify, I want to r ...

Select from a list to save

My goal is to create a feature where users can select a hotel name, number of days, guests, and peak time, the system will calculate them together and give a sum. Furthermore, I wish to store all user selections in the database, including the calculated to ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

What is the best way to format a list <li> inline within PHP code?

Is there a way to display this list horizontally? Using list-inline makes the list horizontal, but it doesn't style the <li> elements. I would like to apply a specific class to the li elements, but I'm unsure where in the code to add the s ...

Trigger a function in jQuery when the DOM undergoes changes

Up until now, I have been utilizing livequery which has served its purpose. However, it tends to slow down the page browsing experience, so I am in search of an alternative solution. I have a function that performs ajax on elements with a specific class l ...

Having trouble invoking an express route on mobile devices using the .click method

I'm experiencing a strange issue where my code works perfectly in Chrome browser but fails to function on my phone. Here's the snippet of code causing the problem: $('#plusSign').on('click', function() { var myLin ...

Content does not become interactive upon the initial loading of the page

I've modified a W3 schools slideshow template to use text instead of dots, but I'm encountering two issues 1: The first image doesn't load when the page loads. Although using a class ID and setting it to active fixes this issue, it leads to ...

How can you correctly conceal an HTML element?

What is the correct CSS syntax for hiding HTML elements? For example, how can I hide a <div> tag? I usually use this code: div {display:none; visibility:hidden;} Does this CSS code work in all major browsers to hide the div element? Specifically, d ...

What functionality does this method perform within React.js?

While going through the process of creating login forms, I stumbled upon this interesting method: handleChange(e) { this.setState({ [e.target.name] : e.target.value }); } I am a bit confused about the setState part in this method. The array brackets ...

Encountering a server issue when sending back a SelectList via ajax

When attempting to fetch data from a database in .NET MVC and populate a dropdown list with it, the following code is used: public JsonResult GetCity(string name) { var cities = from c in context.Cities orderby c.Name ...

Creating a Persistent Top Navigation Bar using Bootstrap and Angular

I am struggling to implement a fixed top navbar in Angular. The structure of my main app.component template is as follows: <page-header></page-header> <router-outlet></router-outlet> The bootstrap navbar is included within my ...

Adjusting the dimensions of the clone when it is being dragged over a droppable area -

$(".drag").draggable({ helper: 'clone', appendTo: "body" }); $( ".drop" ).droppable({ over: function(event, ui) { $(ui.draggable).css({width:'30px',height:'30px'}); }, drop: function( event, ui ) { if($(u ...

Changing the text color of Material UI Accordion Summary upon expansion

How can I update the color of an Accordion summary text in Material UI when it is expanded? <Accordion expanded={expanded === 'panel1'} onChange={handleChange('panel1')} className={classes.root}> <AccordionSummary ...

How can I redirect applications from a web browser to Safari?

Is there a way to redirect applications from a browser to Safari? For Android devices, I have implemented a feature where if a user opens my site through a browser built-in within apps like Facebook or Telegram, they are automatically redirected to Google ...

Incorporating fancybox on a dynamically loaded AJAX page

After searching extensively within this group and on Google, I have yet to find any answers to my problem. It seems that others have encountered the same issue, but existing threads did not provide a solution. So here I am seeking assistance. The question ...

Is there a way to dynamically apply the "active" class to a Vue component when it is clicked?

Here is the structure of my Vue component: Vue.component('list-category', { template: "#lc", props: ['data', 'category', 'search'], data() { return { open: false, categoryId: this.category ...

Updating eventKey Text in React-Bootstrap: A Step-By-Step Guide

Having some trouble changing the text on a selected dropdown button. I'm struggling to figure out how to access it, any assistance would be greatly appreciated. Thank you. return ( <DropdownButton bsStyle={title.toLowerCase()} title={title} key= ...