The function document.getElementById is unable to select multiple elements simultaneously

I've been tackling a loading issue. I have a visible div, #loading, and multiple hidden divs, #message. I also have a JavaScript function.

function loading() {
     setTimeout(function() {
         document.getElementById("loading").style.display = "none";
         document.getElementById("message").style.display = "block";
     }, 500, "fadeOut");
 }

However, the line

document.getElementById("message").style.display = "block";
only targets the first #message div.

function loading() {
  setTimeout(function() {
    document.getElementById("loading").style.display = "none";
    document.getElementById("message").style.display = "block";
  }, 500, "fadeOut");
}
loading();
#loading {
  display: block;
}
#message {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="messages" onload="loading();">
  <div id="loading">
    ...
  </div>
  <div id="message">
    QWERTY
  </div>
  <div id="message">
    123456
  </div>
</div>

Answer №1

It has been pointed out by others that ids should be unique and used only once on a page, hence using classes instead is recommended. In this solution, I have utilized querySelectorAll to select a static list of classes.

Another issue lies in the fact that you appear to be attempting to fade elements using jQuery without actually utilizing jQuery for anything else. I would suggest employing CSS transitions instead. They are simple to implement and eliminate the need for loading a large library. The approach here involves adding new classes, fadein and fadeout, which adjust the opacity of specified elements to zero over a period of three seconds.

function loading() {
  setTimeout(function() {

    // ensure a loader class is used as well, to enable proper transition
    const loader = document.querySelector('.loading');
    loader.classList.add('fadeout');

    // select elements with the message class
    const messages = document.querySelectorAll('.message');

    // iterate over each element and add a fadein class
    [...messages].forEach(message => message.classList.add('fadein'));
  }, 500);
}

loading();
.loading {
  opacity: 1;
}

.message {
  opacity: 0;
}

.fadein {
  transition: opacity 3s ease-in-out;
  opacity: 1;
}

.fadeout {
  transition: opacity 3s ease-in-out;
  opacity: 0;
}
<div class="messages">
  <div class="loading">
    Loading
  </div>
  <div class="message">
    QWERTY
  </div>
  <div class="message">
    123456
  </div>
</div>

Answer №2

It is important to assign unique IDs to your DOM elements. Consider updating your code as follows:

<script type="text/javascript">
function displayMessages() {
  setTimeout(function() {
    document.getElementById("loading").style.display = "none";
    var elements = document.getElementsByClassName('message');
    console.log(elements);
    $.each(elements, function(index, item){
    item.style.display = 'block';
    });
  }, 500, "fadeOut");
}
displayMessages();
</script>
<style>
#loading {
  display: block;
}
.message{
  display: none;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="messages" onload="displayMessages();">
  <div id="loading">
    ...
  </div>
  <div class="message">
    QWERTY
  </div>
  <div class="message">
    123456
  </div>
</div>

Answer №3

ID attribute should always be unique. Repeating the same ID multiple times on a page is not allowed. In case you need to use the same identifier, consider using it as a class or data-id, which can either be identical or different.

Answer №4

To select multiple elements with the same identifier in a document, it is important to use different classes instead of repeating the same id. You can group them by class and then utilize the following methods to select them all:

document.querySelectorAll(".ClassName")

Or

document.getElementsByClassName(".ClassName");

Keep in mind that both approaches will return a collection of all elements in the document that share the specified class name, presented as a NodeList object.

Answer №5

function displayMessage() {
  setTimeout(function() {
    document.getElementById("loading").style.display = "none";
    document.getElementById("message").style.display = "block";
  }, 500, "fadeOut");
}
displayMessage();
#loading {
  display: block;
}
#message {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="messages" onload="displayMessage();">
  <div id="loading">
    ...
  </div>
  <div id="message">
    QWERTY
  </div>
  <div id="message">
    123456
  </div>
</div>

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

How can I iterate through a JavaScript object in a recursive manner?

I am endeavoring to design a function that will generate an output like the following when given an object: <div> reason : ok status : 0 AiStatistics : null CurrentSeasonArenaStatistics : null <div> Player <div> CampaignProgr ...

Using Vue.js to send a slot to a child component in a nested structure

Check out this interesting modal component configuration //modal setup <template> <slot></slot> <slot name='buttons'></slot> </template> Imagine using it like a wizard //wizard setup <template> ...

Transform an object containing key-value pairs into an array of objects that include the key name and its corresponding value

My mind is spinning with this problem... I'm struggling to transform the req.query I receive in Express, which is an object, into an array of objects. I need to pass these to SQL Server as inputs for stored procedures. Here is the data I have - { ...

Determining whether an element possesses an attribute labeled "name" that commences with a specific term, apart from the attribute "value"

I'm planning to use distinctive data attributes with a prefix like "data-mo-". Let's say I have the following elements: <span data-mo-top-fade-duration="600">Title 1</span> <span data-mo-bottom-fade-duration="600">Title 2</ ...

Implementing clickable table rows in React Router Link for seamless navigation

I'm relatively new to working with React. In my project, there is a Component called Content, which acts as a container for two other components - List and Profile. class Content extends Component{ <HashRouter> <Route exact path="/ ...

The d3 hierarchy possesses the capability to compute the average values of child nodes

Looking for a solution with d3 visualization that involves averaging up the value of score on the lowest nodes and dynamically adding that average to the parent node above. It seems like there isn't an easy method in d3 for this task. The desired outc ...

The scrolling speed of the mousewheel in Firefox is notably slower compared to that of Google Chrome

Kindly review this sample link: When I test the above example in Chrome and scroll using the mouse wheel, the page moves up by 100px each time. The Y position is displayed as well. However, if I try the same page in Firefox 26.0 and scroll with the mouse ...

Utilize Jquery to calculate the product of the number inputted into the field

Seeking guidance on multiplying the annual liters (#save-lt) by the average fuel price (#usd). The calculation for what you save per year in liters is functioning correctly. Any suggestions? I believe a variable may be necessary. As a beginner in jquery, a ...

Reverse the order of jQuery toggle animations

Looking for something specific: How can I create a button that triggers a script and then, when the script is done, reverses the action (toggles)? (I am currently learning javascript/jquery, so I am a beginner in this field) Here's an example: ...

How can audio be efficiently streamed to the browser in small chunks using JavaScript?

I am currently working on setting up an internet radio station where I want to easily switch songs and overlay sounds. My goal is to limit the audio rate so that the feed can be adjusted before being sent out. Additionally, I would like to provide continuo ...

jQuery AJAX delivering HTML output upon completion

Currently, I am implementing a jQuery Ajax function to submit the username and password and receive a response. The functionality works seamlessly with the GET method. However, when using the POST method, it successfully sends the data but fails to retur ...

Verify whether the input field contains a value in order to change certain classes

My meteor-app includes an input field that dynamically changes position based on whether it contains content or not. When a user begins typing, with at least one character, the input field moves to the top of the page. In my current approach, I am using a ...

Switch images when hovering

I currently have two dropdown menus called NEW and SHOP. When I hover over the New Menu 1, it should display the corresponding image. Similarly, when hovering over New Menu 2, the related image should be shown in a div with the ".menu-viewer" class. Whil ...

Angular 11 along with RxJS does not support the combineLatest method in the specified type

Hey there, I'm currently working on utilizing the combineLatest operator to merge two streams in Angular, but I keep encountering an error message stating that "combineLatest does not exist on type". I've attempted to move the code into a .pipe() ...

Hover background color not being applied to child elements within Button element in Firefox

Ensuring that my product is SEO-friendly, I incorporated semantic markup using the button element and schema attributes. To separate individual items, I utilized "span" elements while setting hover effects on selected items by adding display:block. This a ...

Is it possible to apply a CSS transform without erasing the existing transform?

Looking for a solution: elem transform translateY(5px) scale(1.2) I want the element to move down an extra 5px on hover elem:hover transform translateY(5px) Is there a way to achieve this without knowing the previous state of the transform? Appr ...

Having trouble passing data from router to View with EJS in Express. Despite trying, still encountering ReferenceError message

I encountered an issue when trying to display form errors to the user. I attempted to pass the errors from the router to my view file. Error Message ReferenceError: e:\2016\passport\views\register.ejs:38 36| 37| <div ...

When incorporating <Suspense> in Next.js, the button's interaction was unexpectedly lost

'use client' import React, { Suspense } from "react"; const AsyncComponent = async () => { const data = await new Promise((r) => { setTimeout(() => { r('Detail'); }, 3000) }) as string; return <div>{d ...

Terminate a targeted recipient following the completion of the on event

I am currently running a node service with socket.io and utilizing an event emitter to send updates based on user context. For example, context A may have users 1, 2, and 3 while context B has users 4 and 5. Once a successful connection is established wit ...

Guide on displaying an array object in MongoDB using React

I'm having trouble figuring out how to display certain data from my MongoDB schema in a React component. Here is my MongoDB schema: const postSchema = new mongoose.Schema({ userID: { type: String }, dateTime: { type: Date, default: Date.now } ...