Modify the text on a button using vanilla JavaScript

Although it may seem like a simple question, I am struggling to change the text on my button.

The code for my button in the web browser console is:

<button class="nav-link active" id="coholder-tab" data-toggle="tab" data-target="#coholder" type="button" role="tab" aria-controls="coholder" aria-selected="true">COTITULAR 1 <i class="fa fa-1x fa-trash ml-3 deleteCoholder" aria-hidden="true"></i></button>

I want to be able to click on deleteCoholder, remove COTITULAR 1 and the trash icon, then set the text to AÑADIR COTITULAR.

To achieve this, I am using a function in Vue and vanilla JavaScript. Here's my code:

<button class="nav-link" id="coholder-tab" data-toggle="tab" data-target="#coholder" type="button" role="tab" aria-controls="coholder" aria-selected="false" @click="changeTab()">AÑADIR COTITULAR</button>

const changeTab = () => {
        let textTab = "COTITULAR 1";
        let tabText = document.getElementById("coholder-tab");
        let coholder_container = document.getElementById("coholder_container");
        let icon = '<i class="fa fa-1x fa-trash ml-3 deleteCoholder" aria-hidden="true"></i>';
        tabText.innerHTML = "COTITULAR 1 " + `${icon}`;
        
        if (coholder_container.classList.contains('d-none')) {
            coholder_container.classList.remove('d-none');
        }

        let trahs = document.getElementsByClassName('deleteCoholder');
        trahs[0].addEventListener('click', function(e){
            document.querySelector('#coholder-tab').innerHTML = 'AÑADIR COTITULAR';

            coholder_container.classList.add('d-none');
        });
    }

I have also tried following this solution, but I still cannot change the text on my button and hide my div. I'm not sure what I'm doing wrong.

Thank you for reading and apologies for my poor English.

Answer №1

It seems like this is the solution you've been looking for. Please find the comments provided below to guide you.

// Using .getElementsByClassName() is not recommended due to its performance implications.
const coholder_container = document.getElementById("coholder_container");
const btn = document.getElementById("coholder-tab");

// This code will execute as soon as the page loads.
btn.innerHTML = "COTITULAR 1<i class='fa fa-1x fa-trash ml-3 deleteCoholder' aria-hidden='true'> ICON HERE</i>";

// You don't need to check for a class before removing it. It will be removed if present, otherwise nothing happens.
coholder_container.classList.remove('d-none');

document.querySelector('.deleteCoholder').addEventListener('click', function(e){
  btn.textContent = 'AÑADIR COTITULAR';
  coholder_container.classList.add('d-none');
});
<!-- The omitted coholder_container element has been included here as a placeholder. -->
<div id="coholder_container"></div>

<button class="nav-link active" id="coholder-tab" data-toggle="tab" data-target="#coholder" type="button" role="tab" aria-controls="coholder" aria-selected="true"></button>

Answer №2

Follow these easy instructions to achieve the desired outcome:

Execute the following codes:

document.querySelector('.deleteCoholder').addEventListener('click', function(){
    document.querySelector('#coholder-tab').innerHTML = "ADD JOINT HOLDER";
})

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

The form inputs within the modal are unresponsive to clicks

I recently began using bootstrap modals and had a separate register/login page from the index. I thought incorporating the login/register form into modals would be a good idea. However, inside the modal, all the inputs are not clickable - only accessible v ...

"When a Vuex mutation modifies the state, the computed property fails to accurately represent the changes in the markup

I've encountered a perplexing issue with using a computed property for a textarea value that hasn't been addressed in a while. My setup involves a textarea where user input is updated in Vuex: <textarea ref="inputText" :value="getInputText" ...

Utilize Node.js to efficiently send emails to a group of subscribed clients

I have a Node.js website on my local system that sends email notifications to users about trending articles or posts. Here's how my code works: app.get('/:articlename', (req, res)=>{ conn.query(`SELECT views,isAlreadySent FROM article_ta ...

What is the interaction between Parse Cloud Code and Parse Server like?

After reviewing Parse's documentation on Cloud Code, I find myself puzzled. They make it clear that Cloud Code is not running in a Node.js environment. What does this mean for the functionality of my server? Even though the server uses Node.js & Exp ...

Sort through the data that is already populated and proceed to paginate within Mongodb

Hey there, I'm currently working on populating some data and then implementing pagination for that data. Take a look at this example: Schema A (Users) { name: 'Demo', postId: 'someObjectId', } Schema B (Posts) { id: 's ...

Securing child paths in Vue.js

Having trouble protecting child routes from parent routes, facing some issues export default new Router({ routes: [ //frontend routes { {path: 'auth', component: Auth, children: authroutes, beforeEnter: (to, from, n ...

What is the best way to include documentation for custom components using jsDoc?

Within my Vuejs inline template components, we typically register the component in a javascript file and define its template in html. An example of such a component is shown below: Vue.component('compare-benefits', { data() { // By return ...

What are the solutions for resolving the TypeError when undefined is not an object error?

I'm currently working on a project where I need to fetch data from a JSON file using XMLHttpRequest and then store it in an array. However, I keep getting errors when attempting to do so. Take a look at this code snippet that seems to be causing the ...

Check the output of the ChildProcess after executing a shell command

I am currently running the ChildProcess function within a Nextjs API route and I am struggling to retrieve the value from it. const output = exec( "curl -s -v https://test.com/index.php", (err, stdout, stderr) => { if (err) { ...

Transform an array of objects into a nested tree structure with Javascript

I am currently facing a challenge with handling a complex json file using javascript to structure it hierarchically. My goal is to convert an array of objects into a deeply nested array, where there can be multiple divNames with varying categories and subc ...

How can I toggle button states within a v-for loop based on input changes in Vue.js?

Within the starting point of my code: https://plnkr.co/LdbVJCuy3oojfyOa2MS7 I am aiming to allow the 'Press' button to be active on each row when there is a change in the input field. To achieve this, I made an addition to the code with: :dis ...

Update the Material UI input field value using an external JavaScript script

Imagine I find myself exploring an online form that utilizes Material UI components, for instance, this example link. I am interested in automatically filling the input fields with a specific value using JavaScript in the console: for (input of document.g ...

Error in Formatting Labels in CSS

I currently have a form with textboxes that include validation. Everything works smoothly when clicking the save button for the first time, but if we fill out the textboxes and then remove the text, an error message is displayed on the textboxes. You can v ...

I have implemented a bootstrap modal, but whenever I trigger a function on the JavaScript side, it automatically closes. I am aiming for the modal to remain open

<div id="responsive-modal3" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none; " data-keyboard="false" data-backdrop="static" ng-init = "populateBidSpocData()" > <div cl ...

Limit User Input to 30 Characters in Vue.js

<script> export default { name: "Register", props: { msg: String, }, }; </script> -------------main.js--------------- new Vue({ data:{ max:30, text:'' }, render:h => h(App), }).$mount('#app' <template> ...

Dynamic links within Vue router can cause issues with page reloading and some components not loading correctly

Within my project's routes file, I have added a new path with nested children: path: '/warehouse/:id', name: 'ShowWarehouse', component: ShowWarehouse, children: [{ path: 'edit', name: 'EditWarehouse ...

The Formik form is not being populated with data from the API

While working on a functional component in ReactJS, I created a simple form using Formik. The input fields in my form are supposed to fetch data from an API when the component mounts. To achieve this, I utilized fetch and useEffect. However, after fetching ...

Issue with rendering HTML tags when replacing strings within Ionic 2 and Angular 2

I am currently working with an array of content in my JSON that includes URLs as plain text. My goal is to detect these text URLs and convert them into actual clickable links. However, I'm facing an issue where even though the URL is properly replaced ...

The Google Maps API allows all markers to be connected to a single infowindow

I've been grappling with this issue for some time now, but I just can't seem to find a solution! I'm retrieving data from a database in Laravel using Ajax and then attempting to display infowindows for each marker on Google Maps. The markers ...

JavaScript Class Emit Signal for establishing a sequence of interconnected events

My Vue project includes a JavaScript class specifically for mobile devices. I'm looking to have this class emit a signal once the property 'hasEnded' is set to True for my object. How can I achieve this and chain together other events based ...