js append square element to dom element in javascript

To append a square element to a DOM element using JavaScript, you can use the createElement method to create an HTML element and the appendChild method to add it to the desired parent element. Here is an example code snippet:

// get the parent element by its ID
const parent = document.getElementById('parent');

// create a new square element
const square = document.createElement('div');
square.style.width = '100px';
square.style.height = '100px';
square.style.backgroundColor = 'red';

// add the square element to the parent
parent.appendChild(square);
332 chars
12 lines

In this example, we first use document.getElementById to get the parent element by its ID. Then, we create a new div element and set its width, height, and background color to make it look like a square. Finally, we use the appendChild method to add the square element to the parent element. This will insert the square element as the last child of the parent.

gistlibby LogSnag