Showing information to several classes using JavaScript

I am currently developing a "Gamebook Engine" that enables users to set a custom username. The user name is extracted from an input element with the id="setUserNameInput" and stored using the function setUserName(). It is then displayed or loaded into an element with the class="displayUserName" through the function displayUserName(). Everything works smoothly when there is only one class on the page, but when additional classes are added, I have to specify which one to target as it does not automatically target all of them. I have experimented with document.getElementById, document.getElementsByName, document.querySelectorAll, and document.querySelector without success. (Just a side note, I am utilizing Bulma as my CSS Framework)

Here is the code snippet I have constructed so far (note: accessing localStorage will result in an error in this snippet): You can find an operational example on this page . Since this is a documentation page hosted on my testing server, you may also want to refer to for details regarding individual elements (please note that the documentation is in German, but I can provide a translation if needed).

The specific section of JavaScript that I am struggling with is mentioned right at the beginning, however, any general improvements or suggestions would be greatly appreciated.

var userNameOutput = document.getElementsByClassName('displayUserName')[0];

function setUserName() {
  var usernameinput = document.getElementById('setUserNameInput').value;
  localStorage.setItem('userName', usernameinput);

  if (!localStorage.getItem('userName')) {
    setUserName();
  } else {
    var storedUserName = localStorage.getItem('userName');
    userNameOutput.innerHTML = storedUserName;
  }
}


function displayUserName() {
  if (!localStorage.getItem('userName')) {
    setUserName();
  } else {
    var storedUserName = localStorage.getItem('userName');
    userNameOutput.innerHTML = storedUserName;
  }
}

window.onload = function displayUserName() {
  if (!localStorage.getItem('userName')) {
    setUserName();
  } else {
    var storedUserName = localStorage.getItem('userName');
    userNameOutput.innerHTML = storedUserName;
  }
}
<input type="text" class="input" placeholder="Your name goes here" id="setUserNameInput">


<input type="button" class="button" value="Set your username" onclick="setUserName()" />



<input type="button" class="button" value="Display on click" onclick="displayUserName()" />
<br> So you shall be called <span class="displayUserName"></span>! But dont worry, <span class="displayUserName"></span>, it will be all fine.

Answer №1

To avoid retrieving the first item in the collection using [0], consider iterating through it using a for...of loop and updating the innerHTML of each element with the class displayUserName.

For instance:

var userNameOutputs = document.querySelectorAll('.displayUserName');

for (let ele of userNameOutputs) {
  ele.innerHTML = userName;
}

Below is the full optimized code structure:

function setUserName() {
  var usernameinput = document.getElementById('setUserNameInput').value;
  localStorage.setItem('userName', usernameinput);
  displayUserName(true); // pass true to avoid recursion
}

function displayUserName(skipSet) {
  var userName = localStorage.getItem('userName');
  
  if (!userName && !skipSet) {
    setUserName();
  } else {
    var userNameOutputs = document.querySelectorAll('.displayUserName');
    
    for (let ele of userNameOutputs) {
      ele.innerHTML = userName;
    }
  }
}

window.onload = displayUserName;
<input type="text" class="input" placeholder="Your name goes here" id="setUserNameInput">

<input type="button" class="button" value="Set your username" onclick="setUserName()" />

<input type="button" class="button" value="Display on click" onclick="displayUserName()" />
<br> So you shall be called <span class="displayUserName"></span>! But dont worry, <span class="displayUserName"></span>, it will be all fine.

View the working example: https://jsfiddle.net/hosney/3pxfybrc/1/

Answer №2

const userNameOutput = document.querySelector('.displayUserName');

The use of querySelector selects the first element found in the DOM with the class name 'displayUserName'.

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 preventing the items inside the <ul> element from displaying?

Struggling to grasp pagination, I can't figure out why the contents of "li" under the "ul" disappear while the "ul" container continues to display despite specifying in the JavaScript that only 6 should be visible on the page. The "ul" and "li" elemen ...

Modifying the button for the ajaxtoolkit:AsyncFileUpload widget

I am currently using the ajaxtoolkit:AsyncFileUpload and I'm curious if there is a way to customize the button that comes with it? <ajaxtoolkit:AsyncFileUpload Width="200" ID="filImageUpload" ThrobberID="imgUploadProgress" OnUploadedComplete= ...

The Label method in the Html helper does not display the id

The creation of the checkbox and its label was done using an HTML helper: @Html.CheckBoxFor(m=>m[i].checkExport) @Html.LabelFor(m=>m[i].checkExport) To customize the label, I added the following CSS in a separate file: input[type="checkbox"] + l ...

Tips for customizing the blinking cursor in a textarea

I am experimenting with creating a unique effect on my website. I have incorporated a textarea with transparent text overlaying a pre element that displays the typed text dynamically using JavaScript. This creates an illusion of the user typing in real-tim ...

Implementing Window.Open function within a jQuery Modal

I've set up my Modal Div like this: <div id="dialog-modal" title="Open File"> <img alt="progress" src="images/ajax-loader.gif"/> </div> When I click the button, the modal appears and I can see the progress icon. <sc ...

Utilize Google Maps API to showcase draggable marker Latitude and Longitude in distinct TextFields

I am currently utilizing the Google Maps example for Draggable markers. My objective is to showcase the latitude and longitude values within separate TextFields, where the values dynamically change as I drag the marker. Once the user stops dragging the mar ...

Show 1 Blog Post on a Separate AngularJS Page

I would like to show only Test Post 1 on the next HTML page titleDetails.html when the user clicks on Test Post 1 in index.html 1) titleDetails() in index.html: <a ng-click="titleDetails(post)">{{ post.title }} </a> 2) Controller Variables a ...

Jest: A guide on mocking esModule methods

In my code, I have a function that utilizes the library jszip to zip folders and files: // app.ts const runJszip = async (): Promise<void> => { const zip = new Jszip(); zip.folder('folder')?.file('file.txt', 'just som ...

Conceal the loading spinner in JQuery once the image has finished loading

I am working with a jQuery function that captures the URL of an image link and displays the image. However, my issue lies in managing the loading process. I would like to display a LOADING message and hide it once the image has fully loaded, but I am strug ...

What changes occurred to module file names following the process of minification?

I'm currently troubleshooting an issue with this particular code snippet: import globalComponents from './global-components'; // ... globalComponents.forEach((component) => { // eslint-disable-next-line no-underscore-da ...

Twilio Group MMS feature experiencing technical difficulties

I currently have a Twilio Trial account with an active number that supports SMS/MMS. My goal is to use this number for group MMS chats, but I am facing some challenges. After following a tutorial on Tut, I attempted to create a basic test using the provid ...

Having trouble with getting the second JavaScript function to function properly?

I am facing an issue with the second JavaScript function. When I click the 'Send Mail' button, it should call the second function and pass it two values. However, the href line (second last line in the first function) is not rendering correctly. ...

The URL requested exceeds the maximum length limit in asp.net, causing a 414 error

I encountered the issue of receiving an "HTTP Error 414. The request URL is too long." While reading through this article, I learned that it is caused by an excessively lengthy query string: Currently in my web.config, I have set maxQueryStringLength to " ...

Having trouble displaying the fancybox helper buttons

I had everything working perfectly, but suddenly it stopped and I can't figure out what went wrong. I just need the left, right arrows, and helper buttons to appear when fancybox is open. Any assistance would be greatly appreciated. PS: All the neces ...

Encountering a "Text creation error" while trying to run a three.js demo on Microsoft Edge using the WebGL context

When attempting to run three.js on Edge, an error message appears stating 'text could not be created. Reason: Could not create a WebGL context.' Even after trying to execute the official three.js example on Edge, the same error persisted, while ...

Guidelines for capturing a div screenshot with javascript

Let's say I have a div containing an image source. <div> <p class="row">With custom CSS</p> <img src="/images/midhun.jpg"> </div> When a button is clicked, I want to display a screenshot of this image in another div. C ...

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

Struggling to retrieve JSON data from the MercadoLibre API while consistently encountering the CORS error?

I have been attempting to access a mercadolibre API that provides JSON data I need to utilize. However, whenever I make an AJAX GET request, I keep receiving the same error: "Response to preflight request doesn't pass access control check: It does n ...

Unusual display of feedback text in Bootstrap 4

When I directly copied this code snippet from Bootstrap 4: <div class="form-group has-danger"> <label class="form-control-label" for="inputDanger1">Input with danger</label> <input type="text" class="form-control form-contro ...