How to Create Page Elements with JavaScript

Create Page Elements with JavaScript

How to Create Page Elements and make them Interactive with Event LIsteners

There are several ways to create page elements with JavaScript, including:

Using the document.createElement() method, which creates a new element with the specified tag name. For example, the following code creates a new div element:

let newDiv = document.createElement(“div”);

Using the innerHTML property to add HTML content to an existing element. For example, the following code adds a new p element to an existing div element with an id of “container”:

let container = document.getElementById(“container”);

container.innerHTML += “<p>Hello World</p>”;

Using the appendChild() method to add a new element as a child of an existing element. For example, the following code adds a new p element as a child of an existing div element with an id of “container”:

let container = document.getElementById(“container”);

let newP = document.createElement(“p”);

newP.innerHTML = “Hello World”;

container.appendChild(newP);

Using the insertAdjacentHTML() method to insert HTML content at a specific position relative to an existing element. For example, the following code adds a new p element before an existing div element with an id of “container”:

let container = document.getElementById(“container”);

container.insertAdjacentHTML(“beforebegin”, “<p>Hello World</p>”);

You can also use any of the above methods to add CSS styles, classes and attributes to the newly created elements.

Coding Example of how to insert page content , html elements into your DOM page.

Coding Exercise to demo how to insert HTML page elements into the page with JavaScript

const ele1 = document.createElement(‘div’);

ele1.textContent = ‘My new element’;

document.body.prepend(ele1);

const output = document.querySelector(‘.output’);

output.innerHTML += ‘<div>Laurence</div>’;

output.innerHTML += ‘<div>Hello World</div>’;

output.style.border = ‘1px solid red’;

const ele2 = document.createElement(‘h2’);

ele2.innerHTML = ‘Laurence Svekis’;

const el = output.appendChild(ele2);

console.log(el);

const ele3 = document.createElement(‘h2’);

ele3.innerHTML = ‘Laurence Svekis’;

const el2 = output.append(ele3);

console.log(el2);

output.insertAdjacentHTML(‘beforebegin’,'<p>Para1</p>’);

output.insertAdjacentHTML(‘beforeend’,'<p>Para2</p>’);

output.insertAdjacentHTML(‘afterbegin’,'<p>Para3</p>’);

output.insertAdjacentHTML(‘afterend’,'<p>Para4</p>’);

const ele4 = document.createElement(‘h3’);

ele4.textContent = ‘Laurence Svekis’;

output.insertAdjacentElement(‘beforebegin’,ele4);

output.insertAdjacentText(‘beforeend’,’Hello World 4′);