Updating the contents of one specific div without affecting all other divs with the same class

Below is the HTML code snippet in question:

<a class="btn test-btn test-btn-1">
  <span>Content 1</span>
</a>

This particular code block appears multiple times on the page. The number at the end of test-btn- is dynamically generated, so it could vary from 1 to 200.

Upon clicking the button, an AJAX function is triggered which adds a new class called test-btn-clicked to the a tag. Once the process is complete, I aim to update the content within the span element to display a different message.

I have attempted several methods to achieve this, but the issue I'm facing is that every button's content gets updated, instead of just the one I clicked.

Can anyone provide guidance on how to approach this problem?

Answer №1

To ensure you target only the current element that was clicked, it is important to note that $(this) may not be accessible within an ajax call due to a change in context from the clicked element to the ajax call itself. To work around this, define the context of the current element before making the ajax call and then utilize that reference to update the clicked element. Here is an example code snippet:

$('.test-btn').click(function(){
 var that = this;
  $.ajax({ 
    url: '#',
    success: function (result) {
      $(that).find('span').text("new span text here");
    }
  });
});

Answer №2

If this function is what initiates the ajax call:

$('.btn').on('click', function() {
   var $this = $(this);
   $this.addClass('test-btn-clicked');
   $.ajax({
     url: "test.html"
   }).done(function(data) {
      $this.find('span').html(data);
   }); 
});

Answer №3

make sure to utilize this in this manner:

$('.test-btn').click(function(){ //
    // insert your code here
    $(this).find('span').text('some text');
});

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

Which is better: JavaScript, Json, or Html?

When working with an ASP.NET MVC view and using jQuery AJAX to update a div, the decision on whether to use a controller that returns a PartialView or JSON can depend on various factors. Consideration for both user experience and system performance is im ...

Is it possible to obtain the socket.id of a user immediately upon their connection?

Does anyone know how I can send a personalized message to a user when they connect, without broadcasting it to everyone else? I'd like to use their socket ID with the code io.to(theirSocketID).emit('chat message', 'Welcome');, but ...

How to retrieve the chosen option from a drop-down menu created within a loop in a React application

I am seeking guidance on the best way to create multiple drop-down menus (<select>) using a loop, so that I can retrieve their selected values using a button. I have attempted to replicate what is currently in my code, hoping this information is suff ...

By employing the actions class for scrolling to the bottom of the page, inadvertently clicking on another element triggers an unintended right-click context menu to appear

Currently, I am implementing Actions to automatically scroll down to the bottom of the page: public void scrollToBottomPage(){ Actions actions = new Actions(driver); actions.keyDown(Keys.CONTROL).sendKeys(Keys.END).perform(); } However, in the fo ...

Is styling in React not showing up?

Currently, I am tackling a third-party pagination component in Reactjs. The npm package instructs me to include the line import "rc-pagination/assets/index.css"; in the file. However, despite injecting the index.css into the DOM using the style loader, I ...

Adjusting the width of the rail in Material UI's vertical Slider component in React

After attempting to adjust the width and height of the rail property on the material ui slider I obtained from their website demo, I have encountered an issue with changing the thickness. import React from "react"; import { withStyles, makeStyles } from " ...

Aligning an SVG icon at the center of a button

I have elements that are currently being used as buttons, but I want to switch them out for actual button tags. This would improve accessibility and allow keyboard navigation using the tab key to focus on my buttons. Each button contains a centered SVG ima ...

Ensure that the Materialize CSS modal form remains open even after submission

Is there a way to reload a form inside a materialize modal with empty fields without closing the modal after submitting? The issue is that currently, when the submit button is clicked, the modal closes and redirects. <div class="modal" id="docM ...

Tips for managing nested objects within React state and keeping them updated

Could someone kindly point out where I might be going wrong with this code? Upon checking the console.log, it seems like the date function is functioning correctly. However, despite using this.setState, the timestamp remains unchanged. Any help would be gr ...

The React DOM element undergoes mounting and unmounting on each render cycle when it should be simply altered/updated

As per the React documentation, callback refs are invoked during both component mounting (with the DOM element's value) and unmounting (with null): When a React component mounts, the ref callback is triggered with the actual DOM element, and when it ...

The H1 tag fails to appear on the webpage

I can't figure out why my H1 is not visible. It seems to be hidden by a div. What's strange is that the parent div is visible when I change the background color to something other than transparent. Even an input tag within the same div displays c ...

Can I restrict access to all routes except one in vue-router? Is this a safe practice? Should I explore alternative methods for achieving this?

I am looking to create an online exam consisting of 5 pages, each with a countdown timer set at 120 seconds and 4 questions on each page. Once the timer runs out, users will be automatically redirected to the next page, or they can manually click the "next ...

Utilizing AJAX to dynamically populate an HTML list from a database and then saving the user's newly selected value back to the database

I'm working on dynamically populating a list from a database using AJAX and then updating the selected value back to the database with a servlet. What's the best approach for achieving this? Typically, I use the following code for dynamic update ...

How can one interpret the act of "passing" an interface to an RxJS Store using angle brackets?

When working with NgRx and typescript, I often come across this syntax within class constructors: import { Store, select } from '@ngrx/store' class MyClass { constructor(private store: Store<AppState>) { this.count$ = store.pipe(sele ...

Enhancing AngularJs code effectiveness through the use of MVC framework

I'm completely new to AngularJs and still trying to grasp the concepts. I have a few questions that I hope someone can help me with: Is it possible to trigger code in the controller only when a button is clicked, rather than having it load with the ...

How can I use PHP to update and select on the same page simultaneously?

Having always been able to do something similar in other languages, I'm facing a few difficulties with PHP. My goal is to load a page that displays all the values from a form (created with a SELECT) and then update them all when clicking a "CHANGE" bu ...

Preventing User Duplication in MERN Stack: Strategies to Avoid Multiple Registrations

A developer fairly new to the field is working on a project using the MERN stack. Within this app, there are two models: one for Users and another for Tournaments. The Tournament model contains an attribute called participants, which is an array. The dev ...

In the Bootstrap Grid system, all posts are aligned to the left side

I have created a gallery with Bootstrap in React.js. The posts are currently displayed using the bootstrap grid system, however, all posts appear on the left side and I am struggling to center them. Any ideas on how to achieve this? After applying justify ...

Error thrown when attempting to access properties of null values (Uncaught TypeError: Cannot read properties of undefined (reading 'map'))

import React, { useState, useEffect } from "react"; import { TaskLists } from "./TaskLists"; import { Daycard } from "./daycard"; import { getTasks, deleteTask } from "../api/task.api"; export function TaskManager() { const [tasks, setTasks] = useState( ...

Use the button to trigger the opening of the datepicker in React material UI

Currently, I am incorporating a Datepicker in my project using React Material UI. <TextField id="datetime-local" label="Next appointment" type="datetime-local" defaultValue="2017-05-24T ...