Swap out a button for another using JavaScript

I am facing a challenge where I need to replace an active button with a deactivate button. The issue is that when I click on the active button, it does change to the deactivate button as expected. However, clicking again does not switch it back to the active state. Can someone help me out with this problem?

<td class="statusButtons">
         <span><a href="#" class='status activeBtn'>Active</a></span>&nbsp;
         <span><a href="#" class='status editBtn'>Edit</a></span>&nbsp;
         <span><a href="#" class='status deleteBtn'>Delete</a></span>
 </td> 

The provided JavaScript code is:

const statusButtons=document.querySelector(".statusButtons");
const status=document.querySelector(".status");
const activeBtn=document.querySelector(".activeBtn");
activeBtn.addEventListener("click",changeA2D);
function changeA2D(){
    activeBtn.style.visiblity='hidden';
    activeBtn.parentElement.innerHTML=`<a href="#" class='status deactiveBtn'>Deactivate</a>`;
}

Answer №1

Instead of modifying the element itself, modify the text inside based on the current state of isActive.

const statusButtons = document.querySelector(".statusButtons");
const status = document.querySelector(".status");
const activeBtn = document.querySelector(".activeBtn");
activeBtn.addEventListener("click", toggleActiveState);

let isActive = true;

function toggleActiveState() {
    isActive = !isActive
    activeBtn.innerText = isActive ? 'Active' : 'Inactive';
}

Answer №2

To improve selection using document.querySelector(), I plan to assign an id to the ActiveBtn element.

<td class="statusButtons">
         <span><a href="#" class='status activeBtn' id ='activeButton'>Active</a></span>&nbsp;
         <span><a href="#" class='status editBtn'>Edit</a></span>&nbsp;
         <span><a href="#" class='status deleteBtn'>Delete</a></span>
    </td> 

Next, I will utilize this script to toggle the button:

let activeButton = document.querySelector("#activeButton");
activeButton.addEventListener("click", toggleActiveStatus);

function toggleActiveStatus() {
    activeButton.classList.toggle("activeBtn");
    activeButton.classList.toggle("inactiveBtn")
    
    let buttonText = activeButton.classList.contains("activeBtn") ? "Active" : "Inactive";
    activeButton.innerText = buttonText;
}

An oversight in Dor Ben Itzhak's answer is forgetting to update the class after the button is clicked.

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

POST requests in Angular Universal are making use of the IP address assigned to my server

My Angular Universal application (version 5.2.11) is currently hosted on Heroku, running on a Node server using express. I have implemented rate-limiters in all my POST routes to restrict requests by IP address, checking the request's IP through req.h ...

What is the best way to display the current time (generated through JavaScript) within a designated div element?

During my JavaScript studies, I stumbled upon the following code snippet: function printTime() { var d = new Date(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); document.body.innerHTML = hours+":"+mins+":"+sec ...

Tips for customizing the appearance of a child component using the parent component in Vue.js

I am working on creating a layout using Vuejs and flexbox that includes elements like 'header, sidebar, main-content, sidebar, footer'. I have separated each part of the layout into individual .vue files, such as header.vue and sidebar.vue. In ...

To generate a new <div> element by clicking a button and then clicking on it using C# Selenium

Before clicking the button, this is the initial HTML code for the page: <div id="layerContainer"> </div> After clicking the button, the code changes as shown in the picture here I have been attempting to locate the new button, but I keep rec ...

Adjust the image's height to adapt to the size of the browser

I'm having trouble resizing the images to match the height of the browser window. My goal is to limit the images' height to a maximum of 1100px and have them scale down based on the height of the browser. I've experimented with setting the ...

Refreshing certain sections of a webpage without the need to refresh the entire page

If you want to understand better, it would be helpful if you could check out my website first at: The main part of the website is a stream from Own3D.tv displayed through an iframe (line 342). My objective is to have the ability to click on a specific str ...

Authorization setup encountered an issue: an unexpected character was found at the beginning of the JSON data on line 1, column

I'm currently in the process of setting up a login page for users on my website, using mongoose, express, bcrypt, and nodejs. However, I am encountering an issue when trying to input the username and password. The error message that I receive is as fo ...

Can you restrict the selection of text to only the current element?

<div class="container"> <div class="item1">text text text in div element 1</div> <div class="item2">text text text in div element 2</div> </div> Is there a way using HTML nodes, CSS, or JavaScript to restrict the select ...

Combining Images Together in JavaScript

In my current javascript project, I've encountered an issue. Specifically, I'm trying to overlay one image on top of another image using the following code: <div> <img src="1.jpg" style="z-index:1;"/> <img src="2.png" style="z ...

What are the steps to changing the navbar's color when scrolling down?

I am having trouble changing the color of my navigation bar from transparent to black after the user scrolls down. Despite trying various methods and watching tutorials, I can't seem to get it to work. HTML <nav role='navigation' class= ...

Accessing table cell value when clicked using JavaScript or jQuery

I am currently working on an ASP.NET MVC application where I have a table displaying records from the database in razor code. My goal is to extract the record ID "FeeZoneID" from a cell value when the delete link in the last column is clicked, and then t ...

Is it acceptable to manipulate the prevState parameter of the setState function as mutable?

It is commonly known that directly modifying this.state is not recommended, and instead setState should be used. Following this logic, I assumed that prevState should also be treated as immutable, and setState should always involve creating a new object i ...

Sending data from PHP to a text file upon clicking a button

I have been struggling with AJAX and despite my efforts to research on Stack Overflow and other online resources, I still can't get it to work. Any help would be greatly appreciated. My issue involves a formatted JSON file that I am able to parse usi ...

Learn how to display a tooltip for every individual point on a Highcharts network graph within an Angular

I am currently working on developing network graphs using highcharts and highcharts-angular within my Angular application. I have successfully managed to display the graph with datalabels, but now I need to implement tooltips for each point or node on the ...

Incorporate interactive click buttons into your Telegram bot

Currently working on a telegram bot using node.js with the telegram-bot API by yagop. https://github.com/yagop/node-telegram-bot-api My goal is to allow users to stop typing messages and instead just click on buttons that will trigger actions. When a user ...

Using HTML5 to display the {{data}} extracted from a JSON file right in the center of the text

Can someone help me with a question about working with html and angular5? <span [innerHTML]="'client.acceptance.explanation'| translate"></span> <span><b>{{data}}</b></span> I have text stored in a json file ...

The dropdown button becomes unresponsive when attempting to navigate within it using ajax requests

Hello fellow members of the StackOverFlow community, I recently implemented a Bootstrap 5 dropdown button to fetch tabs from the backend using AJAX. Everything was functioning correctly until I encountered an issue where, upon clicking a button within one ...

What is the best way to hide a section of an image using the background of a different div?

How can I make the background of div2 cover the image in div1 when setting margin-top=-50px? Code snippet: <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> ...

What is the best way to eliminate spaces when moving to a new line in HTML?

How can I eliminate the gap between the first and second images in HTML when changing lines? <div> <img src='http://lorempixel.com/100/100/abstract/1' /> <img src='http://lorempixel.com/100/100/abstract/2' />< ...

Is it possible to create interlinked HTML pages from markdown files?

Is it possible to create documentation using multiple .md files that reference each other and then utilize a tool like Dillinger to convert these .md files into separate html pages with interlinking? For instance, can I automatically transition (via Dilli ...