append square to dom in javascript

To append a square to the DOM in JavaScript, first create a new HTML element using createElement method and set its dimensions and background color using CSS styles. Then, use the appendChild method to add the new element to an existing parent element in the DOM.

index.tsx
// create a new square element
const square = document.createElement('div');

// set the style of the square
square.style.width = '50px';
square.style.height = '50px';
square.style.backgroundColor = 'red';

// get the parent element in the DOM
const parent = document.querySelector('#container');

// append the square to the parent element
parent.appendChild(square);
369 chars
14 lines

In this example, the newly created square element is appended to an existing parent element with the id of container. You can replace #container with the appropriate CSS selector for the parent element you wish to append the square to.

gistlibby LogSnag