What is the best way to select an individual child element from a JavaScript list?

Looking to create a snow effect on a website, I currently have 5 snow particles falling and want them to randomize their horizontal position after passing through the bottom of the viewport. The issue is that only the first child element seems to get affected by the animation delay. Any insights on how to control this behavior for all snow particles would be greatly appreciated.

let snow = document.querySelector('.snow');

function setProperty(position) {
  snow.style.left = position + "%";
}

function changeAnimationPos() {
    let position = Math.random() * 101;
    setProperty(position);
}

setInterval(changeAnimationPos, 6000)
body {
    margin: 0;
    background: linear-gradient(snow, skyblue);
    background-attachment: fixed;
}

#header {
    margin-top: 5px;
    text-align: center;
    font-family: sans-serif;
    font-size: 40px;
    color: white;
    -webkit-text-stroke-color: black;
    -webkit-text-stroke-width: 0.8px;
    text-shadow: 0px 0px 5px black;
    width: 100vw;
    height: 5vh;
    background-color: snow;
    border-bottom: 3px solid black;
    z-index: 999;
}

/*-----Snow-----*/

.snowfall {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
}

.snow {
    background-color: white;
    height: 10px;
    width: 10px;
    border-radius: 50%;
    border: 1px solid black;
    animation: fall 4s linear infinite;
    position: absolute;
    top: -40px;
    left: 10%;
    z-index: 1;
}

.snow:nth-child(1) {
    animation-duration: 6s;
    position: absolute;
    top: -40px;
    left: 20%;
}

.snow:nth-child(2) {
    animation-delay: 2s;
    animation-duration: 8s;
    position: absolute;
    top: -40px;
    left: 30%;
}

.snow:nth-child(3) {
    animation-delay: 8s;
    animation-duration: 12s;
    position: absolute;
    top: -40px;
    left: 40%;
}

.snow:nth-child(4) {
    animation-delay: 6s;
    animation-duration: 7s;
    position: absolute;
    top: -40px;
    left: 50%;
}

@keyframes fall{
    0% {
        transform: translateY(0);
    }
    100% {
        transform: translateY(110vh);
    }
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8>
        <link rel="stylesheet" href="stylesheet.css">
        <title>Matching Game Project</title>
    </head>
    <body id="body">
        <header id="header">Matching Game</header>
        <div class="snowfall">
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
        </div>
        <script src="snow.js"></script>
    </body>
</html>

Answer №1

Utilizing the querySelector() function will only return the first matching element, as detailed here. If you need to target all elements, consider using getElementsByClassName(). This method will provide an array containing all matching elements that can be iterated over. As mentioned in the comments section, another alternative is querySelectorAll(). One key distinction from getElementsByClassName() is that querySelectorAll() returns a non-live NodeList, while getElementsByClassName() provides a live HTMLCollection.

let snow = document.getElementsByClassName('snow');

function setPosition(element) {
    element.style.left = Math.random() * 100 + "%";
}

let i = 0;
for (const flake of snow) {
    setTimeout(() => setInterval(() => setPosition(flake), 6000), 1000 * i);
    i++;
}
body {
    margin: 0;
    background: linear-gradient(snow, skyblue);
    background-attachment: fixed;
}

#header {
    margin-top: 5px;
    text-align: center;
    font-family: sans-serif;
    font-size: 40px;
    color: white;
    -webkit-text-stroke-color: black;
    -webkit-text-stroke-width: 0.8px;
    text-shadow: 0px 0px 5px black;
    width: 100vw;
    height: 5vh;
    background-color: snow;
    border-bottom: 3px solid black;
    z-index: 999;
}

/*-----Snow-----*/

.snowfall {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
}

.snow {
    background-color: white;
    height: 10px;
    width: 10px;
    border-radius: 50%;
    border: 1px solid black;
    animation: fall 4s linear infinite;
    position: absolute;
    top: -40px;
    left: 10%;
    z-index: 1;
}

.snow:nth-child(1) {
    animation-duration: 6s;
    position: absolute;
    top: -40px;
    left: 20%;
}

.snow:nth-child(2) {
    animation-delay: 2s;
    animation-duration: 8s;
    position: absolute;
    top: -40px;
    left: 30%;
}

.snow:nth-child(3) {
    animation-delay: 8s;
    animation-duration: 12s;
    position: absolute;
    top: -40px;
    left: 40%;
}

.snow:nth-child(4) {
    animation-delay: 6s;
    animation-duration: 7s;
    position: absolute;
    top: -40px;
    left: 50%;
}

@keyframes fall{
    0% {
        transform: translateY(0);
    }
    100% {
        transform: translateY(110vh);
    }
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="stylesheet.css">
        <title>Matching Game Project</title>
    </head>
    <body id="body">
        <header id="header">Matching Game</header>
        <div class="snowfall">
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
            <div class="snow"></div>
        </div>
        <script src="snow.js"></script>
    </body>
</html>

If your goal is to target a specific element, it's advisable to utilize distinct ids or unique classnames.

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

Customized HTML Template Tag

While I understand that using custom html tags is generally frowned upon for various reasons, I have a specific scenario that I believe might warrant the use of a custom html tag. I hope to either be proven wrong or discover a better way of achieving my ob ...

Enhance the state by incorporating a key string in the setState function

Need help with my react component that has input boxes. I want to ensure they are not empty. Upon componentDidMount, I call the function: this.validateInputLength(this.state.first_name, 'firstNameValid'); Here, I am passing in the value of thi ...

How to delete a div element in Material UI's Date Picker

In my project, I am utilizing Material UI's simple Date Picker module. However, I am looking to solely display the calendar section without the month and year indicators along with the navigation arrows. Is it possible to remove these specific element ...

Angular 7 - Implementing periodic JSON data retrieval from server and maintaining local storage within Angular application

Seeking guidance on how to handle updating a static json file stored in the assets directory in an Angular 7 project. The goal is to periodically fetch a json from a server, check for updates, and perform post-processing on the data in the static file (ess ...

Ways to maintain a pointer to a RequireJS module?

Understanding the inner workings of RequireJS has been a bit challenging for me, as the official website doesn't provide clear explanations on fundamental concepts like how to utilize the 'require' and 'define' methods. Currently, ...

Are Your Padding Styles Missing?

I've noticed that the text under the photos on this page in the main section (a.event) is not displaying the 5px padding top and bottom. Any suggestions for fixing this? Thank you! =) a.event { width:315px; height:auto; border:0; padding: 5px 0; } ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

incorporating event handlers to references retrieved from bespoke hooks

I have designed a simple custom hook in my React application to manage the onChange events of a specific input element. const useInput = () => { const ref = useRef(null); const handleChange = () => { console.log("Input has been ...

Can anyone suggest a way to iterate over an object and substitute spaces in the keys?

I need to iterate through a dynamically-created object that contains properties with values. The issue is that the property names in this dynamic object contain spaces, which are not allowed in JavaScript object properties. How can I loop through this ob ...

What is the best way to compile and assess logical operators and operands that are defined within an object?

How can I create a compiler that can evaluate logical operators and operands specified on an object, similar to MongoDB's $or and $and operators? For example: return { $or: [ foo: [...], bar: [...] ] } The compiler would call correspondi ...

Can the identical script be implemented by utilizing two separate JavaScript files?

My knowledge of JavaScript is limited, so I often rely on resources like JavaScript.com and Dynamic Drive for coding. Recently, I came across some scripts that reference two different .js files. <script type="text/javascript" src="lib/prototype.js"> ...

The formValidation, previously known as BootstrapValidator, is causing issues with my form submission via Ajax, despite my efforts to update the code to work with

I recently upgraded the old BootstrapValidator to the new 0.6.0 release known as formValidation. Despite reading the documentation multiple times, I have been unsuccessful in finding the issue and need some assistance. Below are the CSS styles and scripts ...

Could a web-based ACM judging platform be created with Node.js or Python?

Suppose I am looking to develop a traditional online judging system, where the main components include: Receiving users' code and saving it to a file Compiling the code on the server Executing it on the server (while implementing sandbox measures to ...

Detecting modifications to the DOM when there are no identifiable IDs or classes

I'm currently troubleshooting a bug in my Gmail Google Chrome extension where I need to identify when the Rich Format bar is visible. Unfortunately, all the ids and classes are encrypted and unreliable. To locate the message canvas this.canvas_frame ...

Adjust the position of the left margin when resizing

I am working on creating a horizontal slider and need to fix the margin-left value upon resize. Here is the HTML markup I have so far. The sections float left, and the article takes up the width of all the sections. The #mainSlider has a variable width. ...

Decoding JSON - JavaScript - null value

My JSON data is as follows: [ { "0": "324", "1": "Cavill ", "2": "11", "3": "100018463", "4": "RAR", "5": "DummyX", "6": "DummyY", "7": "Moretext", "8": "moretext", "id": "lol", "teacher": "Specsavers ", " ...

Extracting data from a webpage without using Web Locators, Selenium, or Python

xpath_id = '/html/body' conf_code = driver.find_element(By.XPATH, (xpath_id)) code_list = [] for c in range(len(conf_code)): code_list.append(conf_code[c].text) Looking at the situation presented above, I opted for the xpath locato ...

I'm keen on creating a marquee animation using Tailwind and Next.js

I'm working on creating a marquee animation using Tailwind CSS and Next.js, and I've made some progress. However, the issue I'm facing is that the items are not displaying one after the other smoothly; there seems to be a delay when the seco ...

Toggling a modal for a child component in Vue.js

Parent component: <template> <v-btn v-on:click="dialog = !dialog"> </v-btn> </template <script> export default { data: () => ({ dialog: false } </script Child component: <templat ...

Exploration of HTML SVG map image tracking a specific route

Currently, I have an SVG file embedded in my HTML code. The SVG has a viewbox set to 500x500. Within this SVG, there is an Image element that is 2500x2500 in size, depicting a large map. Using Illustrator, I created a path that traces the roads on the ma ...