How to create element in javascript?

In JavaScript, you can create an element using the document.createElement() method. Here’s an example:

// create a new paragraph element
const paragraph = document.createElement('p');

// set the inner text of the paragraph
paragraph.innerText = 'This is a new paragraph created with JavaScript!';

// add the paragraph to the body of the page
document.body.appendChild(paragraph);

In this example, we first create a new p element using document.createElement(‘p’). We then set the text of the paragraph using the innerText property. Finally, we add the paragraph to the body of the page using the appendChild() method.

You can also add attributes to the element using the setAttribute() method:

// create a new image element
const image = document.createElement('img');

// set the src attribute of the image
image.setAttribute('src', 'https://example.com/image.jpg');

// add the image to the body of the page
document.body.appendChild(image);

In this example, we create a new img element and set its src attribute using the setAttribute() method. We then add the image to the body of the page using the appendChild() method.

Leave a Reply

Your email address will not be published. Required fields are marked *