What is the best way to have DOMContentLoaded target all particular div elements?

For my current project, I need visitors to access small pop-up windows for content, but only once a day.

Although I have managed to incorporate part of the script using jQuery, it currently selects only the first div element. How can I modify it to select all specific div elements?

Click here for the code snippet

document.addEventListener("DOMContentLoaded", function() {
  var vlz = document.getElementById("vlz");
  var ls = localStorage.getItem("vlz");
  var data = new Date();
  var data_atual = data.valueOf();
  var data24 = data.setSeconds(data.getSeconds() + 5);

  if (ls < data_atual) {
    vlz.style.display = "block";
    document.getElementById("clz").onclick = function() {
      localStorage.setItem("vlz", data24);
      vlz.style.display = "none";
    }
  }
});
.select {
  padding: 10px;
  background: #eee;
  margin: 10px
}

#vlz {
  display: none;
  width: 250px;
  height: 50px;
  background: #555;
}
<div id="vlz" class='select'>
  <div class='vlz-shw'>
    show
  </div>
  <div id="clz" class='select'>cose</div>
</div>

<div id="vlz" class='select'>
  <div class='vlz-shw'>
    show
  </div>
  <div id="clz" class='select'>cose</div>
</div>

<div id="vlz" class='select'>
  <div class='vlz-shw'>
    show
  </div>
  <div id="clz" class='select'>cose</div>
</div>

Answer №1

Avoid having multiple div elements with the same id; consider using classes instead. There are more modern ways to select elements in JavaScript, such as utilizing querySelector and querySelectorAll.

When selecting elements by class, remember to iterate through them and add event listeners individually.

Check out this functioning fiddle for reference:

document.addEventListener("DOMContentLoaded", function() {
  var vlz = document.querySelectorAll(".vlz");
  var ls = localStorage.getItem("vlz");
  var data = new Date();
  var data_atual = data.valueOf();
  var data24 = data.setSeconds(data.getSeconds() + 5);

  if (ls < data_atual) {
    vlz.forEach(v => {
      v.classList.add('showvlz')
    })
  }

  document.querySelectorAll(".clz").forEach(c => {
    c.addEventListener('click', function(event) {
      // do stuff here
        event.target.parentNode.classList.add('removevlz');
    })
  })
});
.select {
  padding: 10px;
  background: #eee;
  margin: 10px
}

.vlz {
  display: none;
  width: 250px;
  height: 50px;
  background: #555;
}

.showvlz {
  display: block;
}

.removevlz {
  display: none;
}
<div class="vlz" class='select'>
  <div class='vlz-shw'>
    show
  </div>
  <div class="clz" class='select'>cose</div>
</div>

<div class="vlz" class='select'>
  <div class='vlz-shw'>
    show
  </div>
  <div class="clz" class='select'>cose</div>
</div>

<div class="vlz" class='select'>
  <div class='vlz-shw'>
    show
  </div>
  <div class="clz" class='select'>cose</div>
</div>

Answer №2

When coding, it is advisable to utilize classes over ids for better organization. I recommend switching from id to class and using querySelectorAll for improved functionality:

document.querySelectorAll('.vlz')

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

Stop the jQuery custom slide animation when there are no more items to display

I have designed a unique slider for users to view the work process https://i.sstatic.net/FLYne.png When a user clicks the button, the slider will move left or right depending on the button clicked. However, if the user clicks multiple times, the slider ma ...

Ensure that the images within the div have fully loaded before applying the fadeIn effect to the dynamically added content using Ajax and

I am currently developing a website that dynamically loads image pages into a div using jquery's $.ajax function. The issue I am facing is that when the user scrolls to the bottom of the page, the new images are fading in before they are fully loaded. ...

Displaying a div based on the response after it is received using an if/else statement

In my form, each question is on a separate page (div), with the ability to show and hide pages. If a user receives a response from the API with a status of "accepted", they are redirected to a URL. I'm currently trying to display a div if their status ...

Is it possible to have two unique keys in a single MongoDB schema?

Currently attempting to achieve this functionality using mongoose: const newContent = new Schema({ heading: { type: String, unique: true }, url: { type: String, unique: true }, //... }); However, an error is being thrown: MongoError: E11000 dupl ...

Does React trigger a re-render when setState is called even if the state value remains unchanged?

Imagine I create a React component with an initial state of {random: 1}. Now, if I were to execute the following code: this.setState({random: 1}) Would this action result in triggering a re-render of the component? Furthermore, is there a method to avoid ...

Troubleshooting problems with Bootstrap's accordion feature

I've found myself in a tricky situation. I have a set of accordion groups and I need to open them based on certain logic. Additionally, I must be able to have two tabs open simultaneously. The initial tab should also be open when the page loads. I&apo ...

The icons within the <i> tag are failing to appear on my Ionic webpage

Trying to incorporate the tag icon in the HTML, but encountering issues with displaying the icon. Here is the code snippet I am using to display the icon, but unfortunately it's not appearing: <i class="fas fa-plus"></i> Intere ...

What is the best way to access an error's body in order to retrieve additional error message details when using the forge-api with nodejs?

I'm struggling to retrieve the body content when an error is returned from the API request. I've attempted creating a bucket with uppercase letters, but all I receive is an error object with statusCode = "400" and statusMessage = "BAD REQUEST". ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

Is there a way to exclusively show the browser name and version while excluding any supplementary details with 'HTTP_USER_AGENT'?

I am trying to modify my script to only display the browser version and name using 'HTTP_USER_AGENT'. I want to ensure that my script still covers all modern browsers in case someone helps me and specifies the code only for the Safari browser. C ...

react/axios -- encountering issues retrieving data through API request

This is my first time working with React, and I am attempting to make an API call in my code. I found an example online that worked perfectly, so I decided to follow the same approach for my own API call. The call was successful, but when I tried to print ...

Arranging Text and Images in HTML/CSS to Ensure Optimal Placement When the Window Size Changes

Hello fellow coders! I've recently started diving into the world of website development and I have a query regarding positioning elements and handling window resizing. Can anyone help me out? I'm trying to center an image, a message, and a passw ...

Incorporate imagesloaded.js into your PHP script to seamlessly import images from a designated folder

I've implemented the code below into a bootstrap modal to display images from a website folder. These images are loaded using lazyload.js when the modal is opened. Sometimes, there's a delay in displaying images depending on their sizes. I'd ...

Achieving a centrally aligned flex container with left-aligned flex items

My goal is to center the flex items, but when they go onto a second line, I want item 5 (from image below) to be positioned under item 1 instead of centered in the parent container. https://i.sstatic.net/GhD1E.png Here's a sample of my current setup ...

A simple method for bulk editing in Angular UI Grid

Is there a way to enable mass editing in Angular UI Grid by allowing all rows to show editable input fields at once, rather than just one at a time? I have searched online for a solution without success and am now turning to this forum for help. If anyone ...

The toggle in the dialog box refuses to submit the information

I am facing an issue with a dialog box that I am displaying using the jQuery .dialog() function. The dialog box contains a button that I want to use to post back to another page, but for some reason, it is not working as expected. I have tried setting the ...

React/Express: Error 413 encountered when posting due to payload size exceeding limit and Bodyparser failing to handle it

I've exhausted all options but this issue seems unsolvable. I have scoured every single suggested fix on stackoverflow and gone through 3 pages of Google search results. Methods I've attempted Inserted extended: true/false in bodyParser.json U ...

Convert an array into a query string parameter

Currently, I am refactoring some code and attempting to replace the generation of query strings through concatenation with serializing a JSON object. Original Code: $.ajax({ url:'./services/DataService/getDetails?metric=9&'+dashBoards.g ...

The depth buffer in Webgl FrameBuffer is not being cleared properly

Currently, I am working on developing a 2D sprite renderer that utilizes render textures for custom compositing. However, I have encountered an issue where the depth buffer on the FrameBuffer is not clearing properly. Due to this, all the sprites leave a p ...

Converting Form Data to JSON using JavaScript and Ajax POST Request in Laravel

I need to send form data using POST method in JSON format, using Javascript and Ajax in Laravel. Essentially, the form data needs to be converted into JSON for it to be passed with POST to a Controller class which has a method that can handle the data. He ...