Update the innerHTML of several elements with minimal code needed

I have a total of 6 buttons that, when clicked, reveal different div elements below them. I am looking to dynamically change the text content of each button upon being clicked. Managing this for a single button is straightforward:

<input type="checkbox" name="tabs" id="tab-one">
<label for="tab-one" id="one">Read More</label>

... and there are 5 more checkboxes with their respective labels.

var tabLabel = document.getElementById('one');
tabLabel.addEventListener("click", function() {
  if (this.innerHTML=="Read More") {
    this.innerHTML = "Collapse";
  } else {
    this.innerHTML = "Read More";
  }
});

I am seeking guidance on how to adapt this JavaScript code to handle all 6 unique labels effortlessly. Any suggestions would be greatly appreciated.

Answer №1

To store a pair of values within the element, use the data-* attribute to set the .dataset property as JSON. Then, convert it to a JavaScript object in the event handler and update the .textContent with the value from the resulting array that is not the current element. Repeat this process for each element.

onload = () => {
  for (let label of document.querySelectorAll("label[for]")) {
    label.onclick = () => {
      let [curr, next, {textContent}] = [...JSON.parse(label.dataset.t), label];
      label.textContent = textContent === curr ? next : curr;
    }
  }
}
<label for="tab-one" id="one" data-t='["Read More", "Collapse"]'>Read More</label>
<label for="tab-two" id="two" data-t='["Read More", "Collapse"]'>Read More</label>
<label for="tab-three" id="three" data-t='["Read More", "Collapse"]'>Read More</label>
<label for="tab-four" id="four" data-t='["Read More", "Collapse"]'>Read More</label>
<label for="tab-five" id="five" data-t='["Read More", "Collapse"]'>Read More</label>
<label for="tab-six" id="six" data-t='["Read More", "Collapse"]'>Read More</label>

Answer №2

Hey @jackton, here's a neat trick for you: Instead of fetching the element with getElementById in your event handler, you can simply pass it as a parameter. Check out this implementation:

var textArray = ['Hide', 'Show'...]; // Add all your toggle text here

function handleClick(element) {
    let index = textArray.indexOf(element.innerHTML);
    element.innerHTML = textArray[index % 2 ? index - 1 : index + 1];
}

Answer №3

To make use of the event agent, you can attach the event handler to the parent node of the six buttons.

The function for the handler should determine which button has been clicked. You can achieve this by utilizing the event.target property. Subsequently, modify the innerHTML of the target element (the button that was clicked).

var labelsParent = document.getElementById('one').parentNode;
labelsParent.addEventListener("click", function(event) {
    var target = event.target || event.srcElement;
  if (target.innerHTML=="Read More") {
    target.innerHTML = "Collapse";
  } else {
    target.innerHTML = "Read More";
  }
});

Answer №4

Big shoutout to everyone who contributed their answers, but the solution I ended up using was a straightforward forEach loop where each label was assigned the same class. It worked like a charm. Special thanks to @awesomeCoder for also providing a helpful solution.

<input type="checkbox" name="tabs" id="tab-one">
<label for="tab-one" class="one">Show More</label>

var elements = document.querySelectorAll('.one');
elements.forEach(function(elem) {
  elem.addEventListener("click", function() {
    if (this.innerHTML=="Show More") {
      this.innerHTML = "Show Less";
    } else {
      this.innerHTML = "Show More";
    }
  });
});

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

There seems to be a display issue with the DataTables tables

Utilizing Bootstrap 4, I followed the example provided by DataTables on their website: link. The specific code that was implemented can be found here: link Take a look at how it appears: http://pastebin.com/HxSNUnLq Any suggestions on how to resolve th ...

How can I align a fixed-width div beside a floating div that is in percentage?

Having encountered various challenges (not to come across as a complaining troublemaker), my current struggle lies in determining the most effective way to float two divs alongside each other. One with a fixed width and the other with a percentage width to ...

In Angular, leverage RxJS to call a secondary subscription within a pipe operator, enabling the manipulation of a variable from the

I am looking to use a different subscription in order to set a property that originates from a root subscription. Here is the current subscription I have: this.repository.getData(`api/cards/list`) .subscribe( res => { this.data = res as Employee ...

Adjust the class of a div element located close to its ancestor using JavaScript

I'm trying to change the class of the element #sidePanel from .compact to .expanded dynamically in this code snippet: <div id="sidePanel" class="compact"></div> <div id="topbar"> <div id="buttonContainer"> <div ...

Is there an undefined error when clicking on a row in a dynamically created table?

When creating a table and adding a row click event with the purpose of retrieving the value of the first td, the following code is used: function bclick(){ var result=[]; SAPget.step4QueryTable(function(data){ var tbody=document.querySelector( ...

Issue with z-index causing the image to not display when navigating through an image gallery with previous and next buttons using

$(document).ready(function(){ $(".divs div.panel").each(function(e) { if (e > 2) $(this).hide(); console.log(e); }); $("#next").click(function(){ if ($ ...

Checking types in Angular with interfaces

How can strict type checking be implemented in Angular for the returned response? 1. Utilize a data.json file for temporary API purposes [ { "name": "Someone 1", "comment": "comment 1", "line" ...

What is the process for selectively adding interceptors to app.module?

After searching through various topics, I have not found a solution that addresses my specific issue. To provide some context, we have an Angular App that operates in two modes - one mode uses one API while the other mode utilizes a different API. My goal ...

Differences in behavior of Backbone.js Ajax calls between Chrome and Firefox

I am encountering an unusual problem in Firefox. When we load a page and call Routers.initializeRouters(); an ajax request is sent to fetch the data, and the loadFormSuccessHandler function populates the response into the views. In Chrome, the Ajax reques ...

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...

I am encountering difficulty with importing this particular file

I am struggling to get this image to display on my webpage using React. Despite reading through the Facebook documentation, I am still unable to figure it out and feeling quite frustrated. Any help would be greatly appreciated. https://jsfiddle.net/gexcoz1 ...

Easily transform checkboxes into images using jQuery with no need for external plugins

Is it possible to replace checkboxes with images without using jQuery plugins? I'm hoping to achieve this in just a few lines of code. Thank you. ...

How can you ensure that the Data Point Values are always displayed when using arrayToDataTable in the Google Charts API?

Just wanted to clarify that even though there is a similar question titled: Google Charts API: Always show the Data Point Values in Graph ...on this website, I am facing difficulties implementing its solution because my chart is using arrayToDataTable. ...

Strategies for obtaining newly updated data with every request and implementing a no-cache approach in Apollo GraphQL and Angular

Every time a request is made, we need a fresh value, like a unique nonce. However, I am facing issues while trying to achieve this with Apollo's Angular client. My initial solution was to utilize watchQuery with the no-cache strategy: this.apollo.wat ...

Step-by-step guide for integrating a Firebase-exported database into mLab

After exporting my database from firebase, here is how it appears: { "a" : { "-LH-wWiC6Pt874i" : { "OwnerUserId" : "in63Syuyuyighjj", "Passengers" : { "dUCMzvi5UIBd81jPRQhg2" : { "HasPaid" : false, "IsAccept ...

Why does Vue continuously insert undefined values when adding non-consecutive indexes to an array?

In my application, users can select values from a dropdown list and add them to an array by clicking the "add" button. The goal is to use the selected value's id as the index in the array. For example: List of Values 1 - Apple 3 - Bananas 8 - P ...

Expanding the base class attribute in Typescript

I am currently in the process of developing a wrapper class to enhance the functionality of ReactReduxForm's Control component. Below is the initial class/component setup: export class Control<T> extends React.Component<ControlProps<T> ...

Program that extracts information from interactive controls

One of my challenges involves working with pages that have dynamic controls, where I never know the types or quantities of controls present. My goal is to create a script that can extract text from a text area when it's clicked. Although I initially b ...

How can we alert users when data has been updated without the need for a page

The following code was authored by me: $('.actionButton').click(function(){ var buttonValue = $(this).val(); var userId = '<?php echo $_SESSION['id']; ?>'; console.log(userId); ...

Extracting information from the responseText of an XMLHttpRequest

Using AJAX, I am retrieving some data that I need to manipulate after the AJAX call completes. However, I am facing an issue where I can't seem to manipulate the response. Here is the code snippet: function testAjax() { direc = "co ...