Creating a duplicate of a square in JavaScript

For a web development assignment, I am tasked with cloning a square 7 times and increasing its number by 1 each time (from 1 to 8).

I'm considering using a "while" loop with an incrementation until i = 8, but I'm unsure. Also, I'm wondering if it's possible to create a variable with an HTML element inside and then duplicate it.

Answer №1

// Let's create a series of squares and add them to the document
const square = document.createElement('div');
square.style.width = '50px';
square.style.height = '50px';
square.style.margin = '10px';
square.style.backgroundColor = 'blue';
square.innerText = 1;

document.body.appendChild(square);

// Using a simple loop to clone the original square and change the text content
for (let i = 2; i < 9; i++) {
  const clone = square.cloneNode(true);
  clone.innerText = i;
  document.body.appendChild(clone);
}

Answer №2

Explaining how to target elements on a webpage, utilize loops for multiple creations, and modify the content within each element.

// Locates existing HTML elements for JavaScript interaction
const container = document.getElementById("container");
const original = document.querySelector(".square");

// Establishes a constant and variable for looping
const total = 8;
let number = 1;

// Executes a loop while the condition is met 
// (Note: It won't run when number == 8, but it will create square #8 before that)
while(number < total){

  // Updates a value affecting the truth of the condition
  number++;
  
  // Displays information about the current loop iteration
  console.log("creating square number " + number);

  // Duplicates an HTML element
  const copy = original.cloneNode();

  // Modifies the duplicate from the original
  copy.innerHTML = number;

  // Appends the copy to the page by adding it to the `container` element
  container.appendChild(copy);  
}
.square{
  height: 16px; /* Height of the element without padding */
  width: 16px;
  padding: 16px; /* Additional (blue) space included in the element */
  margin: 16px; /* White spacing around the element */
  font-size: 16px;
  text-align: center
 }
.blue{
  background-color: lightskyblue;
}
<div id="container">
  <div class="blue square">1</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

Having Trouble with Text Alignment in jsPDF fromHTML()?

I've been working on generating HTML code for a PDF document using jsPDF. Everything seems to be functioning correctly, except for the alignment of the text. Here's a preview of the generated PDF: https://i.sstatic.net/Kq1jM.jpg My JavaScript c ...

Using logical operators with potential undefined values in TypeScript

I've encountered an error that I'm struggling to fully understand. It seems to be related to the fact that a certain value might be undefined, requiring me to check if it exists. However, when setting up the code as shown below, errors occur. Sur ...

Developing a jQuery loop

I am in the process of creating a function that will change the background color (color A), box color (color B), and text color (color A) when a user clicks on the refresh button. I have already defined an array called 'colors', but I am struggli ...

mentioning the selection menu

Currently, I have implemented this code for verification purposes. <script type="text/javascript> <!-- alert("Testing"); --> </script> After incorporating this code, a popup box appears on the form page as expected. However, my challeng ...

Tips for customizing table cell styling in editable cells with React material table

My code utilizes a material table with editable cells. However, I am encountering a strange style issue when I edit a cell in the table. Please refer to the image below. Can anyone suggest a solution to fix this problem? https://i.sstatic.net/Miiov.png ...

Refresh Next.js on Navigation

Is there a way to trigger a reload when clicking on a Link component from next/link? I attempted to create my own function within the child div of the link that would reload upon click. However, it seems to reload before the route changes and is not succ ...

Creating an element that remains a consistent height despite zooming or resizing the window: A guide with HTML and CSS

Recently, I created a custom scrollbar but faced an issue with its width. Whenever I zoom in or out (Ctrl + mousewheel), the width (set to 10px) changes due to being in pixels. When switched to width: 1vw, it works well with zooming but gets affected by wi ...

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

Receiving a JavaScript function's output with Python Selenium

Currently, I am in the process of scraping data from a specific webpage. The focus is on extracting the return string value from a Javascript function snippet. The target value to be extracted is indicated as "2227885" https://i.sstatic.net/5dLJ ...

Incorporating Scatter Dots into a Horizontal Stacked Bar Chart using Chart.js

My horizontal stacked bar chart is not displaying pink scatter dots based on the right y axis numbers. I need help figuring out what I am doing wrong. When I change the chart to a normal bar instead of horizontal, the dots appear. However, I require them ...

Angular: The elusive "tab" key event fails to trigger

I am facing an issue with a form field and its handler function. I need the handler to be triggered only when the user deliberately accepts the value using either the return/enter key or tabs to the next field. Using the onBlur event is not an option in th ...

R Web Scraping: Navigating Dynamic Web Pages with AJAX Button Clicks

Is there a way to modify the R code below in order to extract Quarterly data? I am attempting to retrieve data from Yahoo Finance, which is a dynamic web page using AJAX, resulting in the same address for both Annual and Quarterly data. The selector to u ...

Can a menu with data-toggle='dropdown' remain visible even after clicking on it?

I have a dropdown menu that I created with the use of data-toggle='dropdown'. Everything seems to be working fine as the buttons close the menu upon clicking, except I would like the gray button (as shown below) to keep the menu open. https://i. ...

Error in Javascript, exception was not handled

I have encountered an issue while using a javascript file named pull.js. This file is meant for implementing pulldown refresh functionality on iPad. However, when I use this file, it seems to interfere with other jQuery and javascript functionalities, caus ...

Exploring the functionality of a Vue component designed solely through a template

I currently have a basic Vue application set up: <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'& ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Is a function repeatedly invoked?

I have implemented a Pagination component in NextJS as follows: import Pagination from 'react-bootstrap/Pagination'; import Router from "next/router"; import {useEffect} from "react"; export { Paging } function Paging(props) ...

ES6 allows for the retrieval of method data within an object

My goal is to improve the organization of my code by creating a config file where I can use the same method to set values. This is just a demonstration, so please keep that in mind. I'm wondering if there's a way to call a function based on wheth ...

Contrast between using " and '

Similar Inquiry: When to Utilize Double or Single Quotes in JavaScript Comparison of single quotes and double quotes in JS As I delve into creating a Node.js Express web application, I've noticed that the tutorial consistently uses ' ins ...

Exploring the possibilities of incorporating Bootstrap 4 or ng-bootstrap elements into Angular 4 development

We are considering the use of Bootstrap 4 within an Angular 4 application by either importing their styles and JavaScript directly, or utilizing ng-bootstrap Angular components for improved performance and compatibility with the Angular app. We would lov ...