Can we create HTML elements in a JavaScript file?

Question

Can we create HTML elements in a JavaScript file?

Answer

We absolutely can! In a JavaScript file, we can use DOM methods and properties to create (or insert, update, delete, etc) HTML elements stored as strings in a JS variable (or as a string passed to a DOM method/property).

However, when using the JavaScript library React, we will normally use JSX to create HTML elements inside a JavaScript file which uses different syntax than we would use if we were using DOM methods/properties.

10 Likes

Thank you for that explanation. It’s pretty clear now to me, however, and example of a DOM method would make it much more evident. Could you provide one?

Thank you.

1 Like

what is stopping you to use google to find the relevant information? Learning to find and understand the information you are looking for is a good skill to have as a developer :slight_smile:

9 Likes

A very convenient answer, though as a paying member I could prefer to hear the answer from the Codecademy staff. Why wouldn’t I use Google to learn all the programming otherwise?

12 Likes

You could, but sites like codecademy offer more structure and order in learning things. Google is great to search for pieces of information you miss or want clarification on.

4 Likes

@juenel @lahinouski some DOM methods are document.getElementById(idName) and . document.querySelector(CSS selector). The JavaScript file must be linked to the HTML file by the tag.

3 Likes

can you explain this question again?

1 Like

Why does this question need explaining again?

It’s good practice to Google these stuff as you won’t be on Codecademy forever! You need to learn to be independent

However, to create an element in vanilla JavaScript, you can do the following:

const h1 = document.createElement("h1");

You then need to add it to your webpage using DOM manipulation. If you want to add classes to it, you can use the classList property

Here’s a good MDN article explaining how this method works: Document.createElement() - Web APIs | MDN

5 Likes

Thank you so much!!!

thanks you so much!!!