Utilize Set.Attribute prior to entering the for loop

Could someone please clarify why I am unable to declare the var node before the for loop and then simply use appendChild(node) inside the loop? Why is it necessary to declare it for each iteration in order for it to affect all div elements? Otherwise, it would just append the textWebinare to the last element. The Variable remains unchanged within my loop and I'm struggling to understand this concept.

NOT FUNCTIONAL:

<div class="video-container">
test
</div>
<div class="video-container">
test
</div>
<div class="video-container">
test
</div>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        var node = document.createElement('div');
        node.setAttribute("id", "textWebinare");
        var video = document.getElementsByClassName("video-container");

        var i;
        for(i = 0; i<video.length; i++){
            video[i].appendChild(node);   
        }
    });
</script>

WORKS:

<div class="video-container">
test
</div>
<div class="video-container">
test
</div>
<div class="video-container">
test
</div>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        var video = document.getElementsByClassName("video-container");

        var i;
        for(i = 0; i<video.length; i++){
        var node = document.createElement('div');
        node.setAttribute("id", "textWebinare");
            video[i].appendChild(node);   
        }
    });
</script>

Answer №1

Think of document.createElement('div') as similar to bringing a new puppy into your life.

Now, imagine video[i] as a designated spot for the puppy and appendChild(node) as placing the puppy in that spot.

If you introduce one puppy and place it in three different spots consecutively, you'll have just one puppy in the final spot, not a puppy in each of the three spots.

To have a puppy in each spot, you must bring in three puppies.


One div cannot simultaneously exist in multiple sections of the same HTML document.

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

React App anchor tag's external links fail to function properly on subsequent clicks when accessed through mobile devices

I have encountered an unusual issue with <a> anchors for external links in my React App on mobile viewports. Initially, clicking an external link opens a new tab just fine on mobile. However, subsequent link clicks on the same or other <a> elem ...

The Dropdown Button Functions Once and Then Stops

I am facing a challenge in implementing a button within an HTML table that triggers a dropdown menu when clicked, and closes upon another click or when the user clicks outside the menu. Oddly, the button only seems to work once before completely losing fun ...

Is there a way to obtain cookies on a Server-side component in the latest version of Next.js?

import axios from "axios"; const Api = axios.create({ baseURL: "http://127.0.0.1:5000", }); axios.defaults.headers.common["Authorization"] = cookie; In server-side environment, document.cookie is not accessible. Alternat ...

Switching visual representation that appears upon clicking the dropdown menu

Issue with Duplicating Dropdown and Image Change const image = document.querySelector('.item__img'); const checkbox = document.querySelectorAll('.imgOption'); function handleChange() { let imgsrc = this.getAttribute("data-value ...

JavaScript failing to load following PHP header() redirect

I've set up a page that allows users to sign in by filling out a basic form, which then sends the data to a separate PHP script for validation. After the validation process is complete, the PHP script uses the header() function to redirect the user to ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Implementing event listeners with AngularJS after making a POST request

As I delve into the world of development, please forgive my lack of knowledge. My search for solutions brought me here. I am currently working on a comment and reply app. In order to add comments to my view, I am utilizing this specific function. $scope.i ...

Activate the 'swipe back' feature within ion-item upon selecting ion-option-button

In my Ionic project, I created an ion-list with ion-items and added ion-option-buttons: <ion-list> <ion-item class="item " ng-repeat="exercise in exercises" on-double-tap="sendToChangeExercise"> <p><h2>{{exercise. ...

How does AngularJS watcher behave when a callback is triggered during a reload or router change?

Can anyone explain why the watch callback is triggered upon browser reload or Angular route change even when the old value and new value are the same? Here's an example: $scope.test = "blah"; $scope.watch("test", function(new, old){ console.log(ne ...

Ways to retrieve text files prior to the webpage loading (synchronously)

I have a simple task at hand that I really want to accomplish - loading some glsl fragment shaders from the disk or server, and then initializing a WebGL web page. Web programming is not my forte; I usually prefer working on shaders and OpenGL in C++. If i ...

Placeholder variable not specified in radio buttons

I am currently facing challenges applying validations to radio buttons in Angular. Normally, I create a #templateRefVariable on the input for other input types, which allows me to access the NgControl and use properties like touched. My goal is to set the ...

What is the best way to incorporate a generated ID into the datepicker() function whenever a button is clicked?

I'm looking to dynamically generate a row of input fields with unique IDs every time the "add another flight" button is clicked, similar to the functionality seen on destina.us. Additionally, I need to incorporate these generated IDs into the jQuery U ...

implementing datepicker on multiple textboxes in jQuery upon button click

I have the ability to show multiple text boxes using jQuery. I am now looking to add a datepicker to those text boxes. Any assistance in finding a solution would be greatly appreciated. Thank you in advance. ...

Steps for resolving the "endless redirection loop" issue in Sharepoint

I am currently learning Javascript and working on setting up a multi-language Sharepoint site. I am trying to implement a code into each page that checks the user's email and the language in the URL (Portuguese or Spanish) and then redirects according ...

Issue with dynamic form JavaScript functionality after removing curly braces { } from a select tag in Rails

In my Rails form, there is a gender field defined as follows: <%= f.select :gender, ["Male","Female"],{class: "gender"} %> I also tried adding an onclick event like this: <%= f.select :gender, ["Male","Female"],{class: "gender"},onclick: "categ ...

Issue when transmitting information from Angular to Express

I'm attempting to send data from Angular to Express.js Below is my TypeScript function connected to the button: upload(): void { const nameFromId = document.getElementById('taskName') as HTMLInputElement; this.taskName = nameFromI ...

Utilize Fb.api to automatically post on user's wall upon logging in

I want to utilize fb.api to make a single post on the logged-in user's wall. Here is the code snippet: var params = {}; params['message'] = 'gegeegeggegall! Check out www.facebook.com/trashcandyrock for more info.'; params['n ...

Obtain module-specific members through programmatic means

When working on a browser, the code may appear like this: //retrieve all enumerable properties of `this` function globalMems() { var g = this; var ret = {}; for (var prop in g) { ret[prop] = g[prop]; } return ret; } In Node.js, this does ...

Form a bond with the latest SignalR library to initiate communication

After attempting to connect to an asp.net core signalR server using the code below, I encountered some issues. Can you spot where I might have gone wrong? Here is the error message that I received: Error: The "promise" option must be a Promise v ...

What is the solution to fixing the error message "SyntaxError: missing ) after argument list" in JavaScript?

I wrote some code in HTML/JavaScript/PHP, and in the 3rd echo statement, I added a button that calls the deleteAttribute() function when clicked. However, I encountered an error at the 3rd echo statement with (type = "button"): "Uncaug ...