Tips for reusing a JavaScript-generated class across a webpage multiple times

I'm currently working on a script that reads a text file and generates an HTML link using a temporary email address.

<script>
//<![CDATA[
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        document.getElementsByClassName('temporary_email')[0].innerHTML = "<a href=\"mailto:" + xhttp.responseText + "\">Email</a>";
      }
    };
    xhttp.open("GET", "/temporary_email.txt", true);
    xhttp.send();
//]]>
</script>

Everything is functioning as planned, allowing me to insert the

<span class="temporary_email"></span>
code snippet anywhere for the link to be displayed.

The issue: I've noticed that I am only able to fetch the email address once. If I have a mailto: link in the body and another one in the footer, the script fails to work. This leads me to believe that there may be something wrong with the way I am handling variables since I am not very experienced with JavaScript yet.

PS: I am attempting to avoid using jQuery. I have tried several simple solutions like duplicating the script and giving it a different name for document.getElementsByClassName, but without success. Essentially, I am looking for a quick and basic workaround until I gain enough knowledge in JavaScript to resolve this issue properly.

Answer №1

The issue why the JS is only added to the first instance of the class name match is because

document.getElementsByClassName()
returns an array of matched elements.

When you use

document.getElementsByClassName('temporary_email')[0]
, it will always target the first matching element.

To resolve this, you must update your code as follows:

var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {

          if (xhttp.readyState == 4 && xhttp.status == 200) {
              var elements = document.getElementsByClassName('temporary_email');

              for (var i = 0; i < elements.length; i++) {
                  elements[i].innerHTML = "<a href=\"mailto:" + xhttp.responseText + "\">Email</a>";
              }  
          }
    };
    xhttp.open("GET", "/temporary_email.txt", true);
    xhttp.send();

Here's a simple fiddle example.

This method allows you to loop through the array and update each element's innerHTML accordingly. Best of all, no jQuery needed!

Answer №2

To update all your temporary_email links, you can iterate through each one and make the necessary changes:

Array.from(document.getElementsByClassName('temporary_email'))
  .forEach(function(el){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        el.innerHTML = "<a href=\"mailto:" + xhttp.responseText + "\">Email</a>";
    }
    };
    xhttp.open("GET", "/temporary_email.txt", true);
    xhttp.send();
  })

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

What is the process for incorporating shaders into a multi-camera renderer in Three.js?

I've successfully created an antialiasing shader with an FXAA pass using Three.js: // Set up scene, camera, and renderer var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(45, 1, 1, 100); var renderer = new THREE.WebGLRenderer(); ...

Ways to implement CSS for limiting the scrollable width of a div element in a web browser

Can anyone guide me on using CSS to limit the scrollable width of a page when the browser is not maximized? An example can be seen on the landing page of When the browser is maximized, there is space around the lady in the picture, but as you reduce the b ...

The menu does not adjust to fit the site properly, causing the video/photos to appear off to the right on smaller screens

Earlier, I received some fantastic help for which I am extremely grateful. However, I find myself in need of your expert assistance once again. The website I am currently working on is . After simplifying the code and removing absolute positioning, I enco ...

Open a customized form in jqGrid when the 'Edit' button is clicked, then refresh the row after editing

Whenever the user clicks on the 'Edit' button in a row of jqGrid, I want to open a customized form. This form should be triggered by the 'OnEdit' event and will display information about the selected row for editing. After making change ...

What is the process behind Twitter's ability to quickly show my profile?

Scenario I was intrigued by the different loading times of Twitter's profile page based on how it is accessed: Clicking the profile link in the menu results in a 4-second load time with DOM and latest tweets loade ...

Is there a way to perform file write/delete/read operations in Python on a different user account sharing the same IP address?

Just starting out as a beginner in Python, I've been exploring how to perform file read/write/delete operations. This has sparked a curiosity in me - is it feasible to access a file in another user's account on the same network, sharing the same ...

The hover effect for Box-Shadow does not appear to be functioning properly in Internet Explorer

When attempting to add box-shadow on a div hover effect in various browsers, I encountered an issue in IE 8 where the text also became shaded. Below are images illustrating the problem: However, in Mozilla, the box-shadow effect is functioning correctly, ...

Looking for assistance in streamlining the code

On my Drupal page, I have multiple divs and a JavaScript function that checks for content inside each one: if ($('.accred').length) { $('#accred').show(); } else{ $('#accred').hide(); } // More code follows... T ...

Incorporate photo thumbnails into Material UI cards

I am currently using Material-UI card component in my React web application. The card is quite plain and only has a title. I would like to enhance it by adding a thumbnail on the left side of the card, followed by the title, similar to how song lists are d ...

Issue Setting Cookies on "localhost" versus "127.0.0.1" Domain - Cookies Disappear Upon Refresh

Encountering difficulties while attempting to set cookies with the domain specified as localhost. Here is what's happening: Upon setting the cookie with localhost as the domain, an error is triggered indicating that the domain attribute is not valid ...

The position of the parent element's bounding box in relation to the child element

I've been mulling over this question for quite some time now, and I finally decided to bring it up. Hopefully, it's straightforward and not something that has been addressed before... Here's the scenario: I have a list of items with anchor ...

What is the best method to assign values to AngularJS controller variables using Python Selenium or the JavaScript console?

After utilizing Python Selenium and AngularJS for a few months, I am currently attempting to adjust certain AngJS variables (specifically the aslider filter from here) and refresh the page in order to extract some data. Below is the code I am using for thi ...

Display Information in Tooltip Using Text from a Different Source

I'm seeking a way to create tooltips on a webpage that provide definitions for specific words. However, these definitions are located on a separate page within the same website. Is it possible for me to extract the text I need to display in the toolti ...

Responsive websites won't function properly

Hello all, I am currently working on centering my Navigation at screen sizes of 320 pixels or less. My goal is to have the logo centered at the top, followed by a centered navigation below, and then everything else aligned accordingly. However, I seem to b ...

Generating as many fields as chosen

Seeking assistance with WordPress. I have set up a custom field named Select number of workers, which includes a select list ranging from 1 to 10 options; My query pertains to generating the corresponding number of input fields based on the selected numbe ...

EJS not displaying object values properly

I'm currently in the process of setting up a blog and I want to create a page that displays the titles of all the articles I've written. For example: List of Articles: * Title: Article 1 * Title: Article 2 * Title: Article 3 Below is my Schem ...

"Integrating Associated Models with Sequelize: A Step-by-Step Guide

I am attempting to retrieve all transactions along with their associated stripePayments, but I keep encountering the error include.model.getTableName is not a function. In my database schema, there is a table for transactions that has a one-to-many relati ...

Ways to display object data in a snackbar within an Angular application

I am currently working on a snackbar feature that receives notifications from a Web Service and displays whether the Job Execution was successful or failed. To parse the JSON data, I have implemented the following code: this.messageService.messageRec ...

Is there a way to arrange list items to resemble a stack?

Typically, when floating HTML elements they flow from left to right and wrap to the next line if the container width is exceeded. I'm wondering if there's a way to make them float at the bottom instead. This means the elements would stack upward ...

I am looking to emphasize text in alignment with the slide image

I'm currently in the process of building a movie information page similar to what you see in cinemas, where I pull images and titles from an external source. The goal of my code is to dynamically highlight the title corresponding to each image when t ...