DEV Community

Cover image for Creating HTML DOM elements with Javascript
Josephine Luu
Josephine Luu

Posted on

Creating HTML DOM elements with Javascript

If you're reading this then you must know a little bit about what HTML and Javascript is. So how exactly do you create a HTML DOM element with Javascript? It's not an easy concept to grasp as a beginner in Javascript but hopefully after reading this, you can gain a better understanding. Let's start with the basics.

What is a HTML element?

A HTML element includes everything in between the first tag to the end of the tag. For example,

<p>A paragraph</p>

Not all HTML files include tags like a paragraph tag <p></p> or an image tag <img>. Knowing how to create a HTML tag with javascript is essential if you want to add anything to the page without touching the HTML file.

How do you create a HTML DOM element with Javascript?

We will use this HTML code in reference to our code examples.

<body>
    <div id='create-cat'></div>
</body>
Enter fullscreen mode Exit fullscreen mode

1) Create an element by using document.createElement("x").
X represents any element you're trying to create.
For example, if you want to create the element <img>
and declare it as a variable, you will type:

 let imgTag = document.createElement("img")
Enter fullscreen mode Exit fullscreen mode

2) Select where you want to append the <img> tag. In this case, append it to the <div> tag. Declare it as a variable so you can reference back to it later. To do that, you will type:

let catCreation = document.querySelector("#create-cat")
Enter fullscreen mode Exit fullscreen mode

3) Now, to actually append the <img> tag under the div tag, you will type:

catCreation.append(imgTag)
Enter fullscreen mode Exit fullscreen mode

This will make the code on the HTML DOM look like this now:

<body>
    <div id='create-cat'></div>
    <img>
</body>
Enter fullscreen mode Exit fullscreen mode

4) To make an image show, you will need to include the source path to the image. So, you will type the variable name you used to create the <img> tag. Enter .src after and set it equal to the image file or link. See the example below:

imgTag.src="img.cat_jpg"
Enter fullscreen mode Exit fullscreen mode

Now you should see the cat image and and the HTML DOM will now look like this:

<body>
    <div id='create-cat'></div>
    <img src="img.cat.jpg">
</body>
Enter fullscreen mode Exit fullscreen mode

Success! You have officially created a new HTML DOM element and appended it. Best of luck coding!

Cover image source: https://www.canto.com/blog/insert-image-html/

Top comments (0)