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

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...

Adding a JavaScript variable into a Django template tag

This particular situation has been presenting a challenge for me. So far, I have been using query parameters instead of a variable within the {% url %} tag. However, I can't help but wonder if there is a way to achieve this: I am interested in includ ...

Tips for transferring this text to a new line

I have come across this text that needs to be moved to a new line, This is its current appearance, Here is how I want it to look: HTML code snippet: <div id="content"> <div id="header"> <p> <img class="header-im ...

Applying the CSS property overflow-x: hidden will prevent horizontal overflow and only display

When I set overflow-x: hidden on an element that overflows both horizontally and vertically, it displays a vertical scroll bar along with hiding the horizontal overflow. I attempted adding overflow-y: visible and just overflow: visible, but it had no effec ...

What is the best way to populate a text field in AngularJS with multiple selected values?

Seeking assistance with a dynamic text field value that changes based on an AngularJS post request. I am looking to modify this value through multiple selected options. Here is the HTML code: <tr ng-repeat="opt in myData"> <td> & ...

What could be causing the server to return an empty response to an ajax HTTP POST request?

Attempting to make a POST request using ajax in the following manner: $.ajax({ type: "POST", url: 'http://192.168.1.140/', data: "{}", dataType: "json", ...

Is there a way to modify the background hue of an upward facing triangle when a submenu is hovered over?

Access the Code on Fiddle #nav .submenu:before { content:""; position: absolute; width: 0; height: 0; border-bottom: 22px solid #b29600; border-left: 11px solid transparent; border-right: 11px solid transparent; margin: -12px ...

Divide Chinese Characters

Is there a way to split foreign characters like Chinese into separate array values using JavaScript? While the split() function works well with English, it doesn't seem to handle Chinese characters properly. Take a look at the results from two string ...

The size of the Tweet button iframe is set at 107 pixels

Has anyone been able to successfully adjust the size of the tweet button generated by Twitter's iframe code? My attempts have resulted in a default width of 107px, but I need it to match the actual button size. I've tried adjusting the CSS proper ...

Vanishing essence

http://jsfiddle.net/ddGHz/1004/ //html <div id = "anglereturn"/> <div class="box"></div> //js, jquery var box=$(".box"); var boxCenter=[box.offset().left+box.width()/2, box.offset().top+box.height()/2]; $(document).mousemove(function ...

Problem with items overlapping in hoverable drop-down menu

I have been attempting to create a hoverable dropdown menu, but I am encountering an issue where the items of the dropdown are overlapping. Despite my efforts to adjust the CSS classes, I have not been successful in fixing this problem. Additionally, I ha ...

Is the concept of client fanout truly beneficial?

I'm in the process of constructing a community platform on firebase that features timelines and posts similar to those found on Facebook. When a user creates a post, it should automatically appear on the timelines of their followers. Google proposes ...

Designing a personalized carousel component in Angular

Looking to replicate this design, any tips? I'm aiming for a carousel layout with developers listed in a project, where the center item is larger than the others. Any guidance on how to achieve this look? ...

Using Java beans to present form data utilizing session

How can I utilize Java Beans and session beans to store user input data and display a preview of the entered details on the next page? I have already created a servlet using JSP, but now I want to incorporate Java Beans to showcase the form data. How shoul ...

Getting POST data in Next.js is a common task that requires understanding of how the

I am currently working on a form validation project using the App Router within Next.js. // app/register/page.tsx export default function Register(context: any) { console.log("Register page", context.params, context.searchParams); return ...

Real-time changes may not be instantly reflected in the model update

I need to add two numbers together and display the sum in a third input field: HTML <div ng-app="myApp"> <div ng-controller="MainCtrl as mainCtrl"> Main {{mainCtrl.foo}} <br/> <input type="text" ng-model="mainCtrl.foo"/> ...

Unable to make an AJAX call to a Spring controller

I am currently attempting to make an ajax call to a Spring controller, but I am encountering an Error 405 stating "Request method 'POST' not supported." I have included my code below and would appreciate any suggestions on how to resolve this iss ...

Conceal a div element after initial visit

There is a button (B) that displays a menu (C) when clicked, and a pop-up (A) that also shows the same menu (C) when clicked. There are 4 tasks to accomplish here. 1) Clicking B reveals C. 2) Clicking A reveals C. 3) Clicking B hides A. 4) A should be hi ...

What is the best way to create a repeating Jquery loop in code?

Hey there! I've been working on creating a button that toggles the background color from white to yellow and back again using Jquery. However, I've hit a bit of a roadblock with implementing a loop function. If you'd like to take a look at m ...

Performing an Ajax request to load a partial view upon successful completion of another ajax request

I am struggling with updating values in a partial view after a form is submitted. The current setup involves rendering another partial view upon submission, but I am looking for a way to trigger a re-render of the initial partial view once the second one h ...