JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript html dom elements (nodes).

Adding and Removing Nodes (HTML Elements)

Creating New HTML Elements (Nodes)

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

 Example

Example explained .

This code creates a new <p> element:

To add text to the <p> element, you must create a text node first. This code creates a text node:

Then you must append the text node to the <p> element:

Finally you must append the new element to an existing element.

This code finds an existing element:

This code appends the new element to the existing element:

Advertisement

Creating new HTML Elements - insertBefore()

The appendChild() method in the previous example, appended the new element as the last child of the parent.

If you don't want that you can use the insertBefore() method:

Removing Existing HTML Elements

To remove an HTML element, use the remove() method:

The HTML document contains a <div> element with two child nodes (two <p> elements):

Find the element you want to remove:

Then execute the remove() method on that element:

The remove() method does not work in older browsers, see the example below on how to use removeChild() instead.

Removing a Child Node

For browsers that does not support the remove() method, you have to find the parent node to remove an element:

This HTML document contains a <div> element with two child nodes (two <p> elements):

Find the element with id="div1" :

Find the <p> element with id="p1" :

Remove the child from the parent:

Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:

Replacing HTML Elements 

To replace an element to the HTML DOM, use the replaceChild() method:

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

how to create html javascript

Get certified by completing a course today!

Subscribe

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Your Suggestion:

Thank you for helping us.

Your message has been sent to W3Schools.

Top Tutorials

Top references, top examples, web certificates, get certified.

SoftAuthor

JavaScript Tutorials

JavaScript CLASS Attribute

JavaScript script attributes

JavaScript DOM

JavaScript Functions

JavaScript Events

JavaScript Images

JavaScript Higher Order Functions

JavaScript Forms

JavaScript AJAX

JavaScript Menu

JavaScript MVC

3 Ways To Create HTML Element In JavaScript

how to create html javascript

Learn how to create html element in JavaScript in a few different ways

Using Just createElement()

Create a div HTML Element in JavaScript by calling the createElement() method on the document object.

This method takes an argument which will be the HTML Element.

In this case… div .

Assign it to the constant called box .

Set the id property of box to ‘ box ‘.

Add it to the DOM hierarchy by calling appendChild() on the document.body object with an argument box .

Let’s add a child element to the box element.

To do that, create a button HTML Element in JavaScript by calling the createElement() method on the document object.

This method takes an argument…

but this time, button .

Assign it to the constant called button .

Add text to the button element by setting a string value to the innerHTML property of it.

Append the button element to the DOM hierarchy by calling the appendChild() method on the document.body object with button as an argument.

To add an ID attribute to the button, set a string value to the id property of button .

Finally, add the button element to the box element.

Call the appendChild() method on the box by passing button as an argument.

Try it out! ⛹️

See the Pen Create HTML Element in JavaScript by Raja Tamil ( @rajarajan ) on CodePen .

Object.Assign()

Learn how to create the same HTML Elements using Object.assign()

Call the assign() method on the object inside appendChild().

Assign method takes two arguments:

This is easier than the previous approach if we have a lot properties.

In order to add a child element to the box element, all we have to do is just chain another appendChild() with a button element.

Which is easier and more readable than the first approach.

See the Pen Create HTML Element in JavaScript – 2 [EMBED] by Raja Tamil ( @rajarajan ) on CodePen .

ES 6 Backticks

Learn how to add the same HTML Elements to the DOM hierarchy using ES6 back-ticks which is by far the easiest.

Because, you can literally write HTML code inside JavaScript which is super easy to read and maintain.

Create a constant called box and add a pair of back-ticks. Write your HTML code exactly as you do inside the HTML page.

Assign it to the innerHTML property of the document.body.

That’s it.

See the Pen Create HTML Element in JavaScript – 3 [EMBED] by Raja Tamil ( @rajarajan ) on CodePen .

Hey, Like what you're reading? Check this out!

A Complete Vue JS & Google Maps API Course Build 3 Location-Based Web Apps Like A Pro!

Valid until aug 31st 2020, ▶️ free course (valued $9.99).

Vue JS2 & Google Maps API Course 1 HOUR Build A Location Detector App

Access the course now.

DEV Community

DEV Community

Cover image for 3 Easy Ways to Generate HTML with JavaScript

Posted on Sep 15, 2022

3 Easy Ways to Generate HTML with JavaScript

In today's post, I'll be taking you through 3 of my favorite techniques to generate HTML using JavaScript.

Video Tutorial

If you prefer, you can consume this tutorial in video form 👇

1. Build HTML Element Objects

We're going to start off strong. This technique involves creating DOM elements using document.createElement(...) and then appending those elements to the document.

It may seem a little cumbersome doing it this way, but it gives you the most flexibility . This means you're able to gain access to the DOM objects immediately and do things like attach event listeners, update attributes or inject text.

Existing HTML

Let's add another list item, Grapes .

As you can see it's very programmatic but provides the most flexibility.

2. innerHTML

If you've dabbled in JavaScript before, you'll probably know about the innerHTML property. This one allows you to re-assign the HTML within an element.

Let's re-add the Grape item from above, this time using innerHTML .

As you can see, I've used += to append to the existing HTML. To replace the entire HTML of an element, simply use = instead.

Another thing to note is that innerHTML is good for simple operations. We've had to use getElementById() once the list item was added in order to add attributes safely .

3. insertAdjacentHTML

This is one of my favourites. The insertAdjacentHTML method works in a similar fashion to innerHTML in that it allows you to inject HTML strings.

However, with insertAdjacentHTML , you're able to specify a position . One of 4 options is available:

Let's see the same example as above, this time with insertAdjacentHTML :

This one still requires you to select the element once it's added, but it provides greater flexibility in terms of positioning of the HTML string.

For more info on this method, see the MDN Docs .

Enrol Now 👉 JavaScript DOM Crash Course

If you're learning web development, you can find a complete course on the JavaScript DOM at the link below 👇 https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1

Course Thumbnail

Top comments (1)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

naubit profile image

That was a nice read! Liked, bookmarked and followed, keep the good work!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

Visualizing Promises and Async/Await 🤓

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓

michaeltharrington profile image

What's the biggest mistake you've ever made while coding?

Michael Tharrington - Mar 1

mahmoudessam profile image

Python challenge_22🐍⚔️

Mahmoud EL-kariouny - Feb 22

defidelity profile image

Protect Your Sensitive Data: A Guide to .env Files in Django

Amusat Haki Adeyemi - Feb 22

djsmk123 profile image

Is your Flutter application Secured? Best Practices for Developing and Deploying Secure Flutter Apps

Md. Mobin - Mar 3

Once suspended, dcodeyt will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, dcodeyt will be able to comment and publish posts again.

Once unpublished, all posts by dcodeyt will become hidden and only accessible to themselves.

If dcodeyt is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Dom (dcode).

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag dcodeyt:

dcodeyt consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging dcodeyt will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Document.createElement()

In an HTML document, the document.createElement() method creates the HTML element specified by tagName , or an HTMLUnknownElement if tagName isn't recognized.

A string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName . Don't use qualified names (like "html:a") with this method. When called on an HTML document, createElement() converts tagName to lower case before creating the element. In Firefox, Opera, and Chrome, createElement(null) works like createElement("null") .

An object with the following properties:

The tag name of a custom element previously defined via customElements.define() . See Web component example for more details.

Return value

The new Element .

Note: A new HTMLElement is returned if the document is an HTMLDocument , which is the most common case. Otherwise a new Element is returned.

Basic example

This creates a new <div> and inserts it before the element with the ID " div1 ".

Web component example

The following example snippet is taken from our expanding-list-web-component example ( see it live also ). In this case, our custom element extends the HTMLUListElement , which represents the <ul> element.

If we wanted to create an instance of this element programmatically, we'd use a call along the following lines:

The new element will be given an is attribute whose value is the custom element's tag name.

Note: For backwards compatibility with previous versions of the Custom Elements specification , some browsers will allow you to pass a string here instead of an object, where the string's value is the custom element's tag name.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Data Structure

How to add a new element to HTML DOM in JavaScript?

In this article we are going to discuss how to add a new element to HTML DOM in JavaScript.

The Document object provides a method createElement() to create an element and appendChild() method to add it to the HTML DOM. Following are the steps involved in creating HTML DOM −

Step 1 − To insert an element into HTML DOM, firstly, we need to create an element and append to HTML DOM. The document.createElement() is used to create the HTML element. The syntax to create an element is shown below.

tagName is the name of the tag to be created. The tag is of <p> type.

options param is an optional element object.

Step 2 − After creation of a tag, we need to create a text to assign to the tag. The syntax to create a text node is shown below.

Step 3 − After creating the text, we need to add the text to the element <p> type and thus finally adding to the div tag. The syntax to append the element to a tag is shown below.

In the following example, initially the div section consists of only 2 texts. But later on, one more text is created and added to the div section as shown in the output.

On executing the above code, the following output is generated.

The following is an example program on how to add an element to HTML DOM.

The following is an example program on how to add an element to HTML DOM. Here, the insertBefore method is used instead of append method to add the element to the div tag.

Lokesh Yadav

0 Followers

Tutorials Point

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Dynamically creating HTML elements using Javascript?

I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don't want to write the HTML code in the following function to some div, but, I want to return it in a var.

How can I do this?

10 Replies's user avatar

6 Answers 6

[ Edit 2021/10 ] This answer is now > 10 years old. Here is a snippet containing several ways to create and/or inject elements. The answer for the question asked ( create some element(s) and retrieve their html code ) can be found @ the bottom of the snippet.

// The classic createElement // ------------------------- // create a paragraph element using document.createElement const elem = document.createElement(`p`); elem.id = `myBrandnewDiv1`; // put in some text elem.appendChild(document.createTextNode(`My brand new div #1`)); // append some html (for demo, preferrably don't use innerHTML) elem.innerHTML += ` =&gt; created using <code>document.createElement</code>`; // append a new paragraph within #myBrandNewDiv1 const nested = elem.appendChild(document.createElement(`p`)); nested.classList.add(`nested`); // add some text to that nested.textContent = `I am nested!`; // the elements are still in memory, now add the // whole enchillada to the document document.body.appendChild(elem); // insertAdjacentHTML // ------------------ // nest an element within the nested div nested.insertAdjacentHTML(`afterbegin`, `<div id="nestedWithin#nested"> This text will appear <i>above</i> the text of my parent, that being div#nested. Someone had the nerve to insert me using <code>insertAdjacentHTML</code> </div>`); // Object.assign // ------------- // Use Object.assign to create an element and // assign properties/html to it in one go const newElem = Object.assign( document.createElement(`div`), { id: `myBrandnewDiv2`, innerHTML: `div#myBrandnewDiv2 signing in. I was <i>assigned</i> using <code>Object.assign</code>&hellip;`}); document.body.appendChild(newElem); // insertAdjacentElement combined with Object.assign // ------------------------------------------------- // use the above technique combined with insertAdjacentElement newElem.insertAdjacentElement( `beforeend`, Object.assign(document.createElement(`span`), { id: `myBrandnewnested2_nested`, innerHTML: `<br>Me too! And appended I was with <code>insertAdjacentElement</code>` }) ); // createDocumentFragment // ---------------------- // Use a document fragment to create/inject html const fragment = document.createDocumentFragment(); const mdnLnk = `https://developer.mozilla.org/en-US/` + `docs/Web/API/Document/createDocumentFragment`; fragment.appendChild( Object.assign( document.createElement(`p`), {innerHTML: `Regards from <code>createDocumentFragment</code> (see <a href="${mdnLnk}">MDN</a>)`}) ); document.querySelector(`#myBrandnewDiv2`).appendChild(fragment); // Create, but don't inject // ------------------------ const virtual = Object.assign( document.createElement(`p`), { innerHTML: ` <a href="#id1">id1</a> <div id="id2">Hi!</div> <p id="id3">Hi 2!</p>`, classList: [`xyz`], } ); const prepareHtml4Reporting = html => html.replace(/</g, `&lt;`) .replace(/\n\s+/g, `\n`) .replace(/\n\n/g, `\n`); document.body.insertAdjacentHTML( `beforeend`, `<h3>html only</h3><pre>${ prepareHtml4Reporting(virtual.innerHTML)}</pre>`); body { font: normal 12px/15px verdana, arial, sans-serif; margin: 2rem; } code { background-color: #eee; } .nested { margin-left: 0.7rem; max-width: 450px; padding: 5px; border: 1px solid #ccc; }

I have used some of these methods in this library (see /src/DOM.js ), with a mechanism for sanitizing html before it is injecting.

KooiInc's user avatar

JavaScript:

The main reason to use a documentFragment in stead of just adding the elements directly is speed of execution.

At this size it doesn't matter, but when you start adding hundreds of elements, you will appreciate doing it in-memory first :-)

With documentFragment you can construct a whole tree of DOM-elements in-memory and will not afffect the browser DOM untill the last moment.

Otherwise it forces the browser to update for every element, which sometimes can be a real pain to watch.

Guidhouse's user avatar

If you're doing this repeatedly (dynamically creating HTML), you might want to use a more general approach.

If you want to create three unrelated elements, you can do:

Now, you have three elements. If you want to get the HTML of these (as string), simply do:

If you want to have these three in an element (say, div), do:

You can get the HTML with div.outerHTML , or you can just append it anywhere you want.

To know more about elem() , visit element.js (GitHub) .

I'm adding this answer not for the 8 year old question, but for the future visitors. Hope, it helps.

akinuri's user avatar

You can construct the html as a string in one variable like

then you return the variable html

Sufendy's user avatar

The better way would be to Import ElementsJS and just reference each element in it.

var root = document.getElementById("root"); var elementdiv = create_element('div',{'class':'divcss'}, root, null); create_element('h1',{'class':'hellocss'}, elementdiv, "Hello World"); .hellocss { color : red; } .divcss { background-color : blue; height: 100px; position: absolute; } <script src="https://elementsjs.blob.core.windows.net/public/create-elements.js"></script> <body id="root"></body>

For More Details Refer to https://github.com/divyamshu/Elements-JS Well Documented with Example.

Divyamshu Gupta's user avatar

Here's simple illustration for converting the html-page (static), to javascript based html-page (dynamic).

Let us say, you have html-page as "index.html" (calling index_static.html here).

index_static.html

You can open this file in the browser, to see the desired output.

Now, lets create a javascript equivalent to this. Use online-tool , to generate the javascript source (by pasting the above html file source to it). Therefore, it follows as:

And now, your dynamic version of the static_index.html will be as below:

index_dynamic.html

Open the index_dynamic.html on the browser to validate the web-page (dynamic though, down-the-line).

parasrish's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged javascript html dom or ask your own question .

Hot Network Questions

how to create html javascript

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

how to create html javascript

Nov 18, 2018

Learn how to dynamically create HTML elements with plain JavaScript

The majority of JS frameworks uses some sort of techniques to handle or manipulate the Document Object Model (DOM) tree. The DOM makes it possible for programs such as JavaScript to change the document structure, style and content. The HTML elements on a page is simply a tree of nodes and objects that together provides structure for showing text, link, image, video and so forth.

The purpose of this article is create a list of bookmarks, and present the URLs using plain JS. The underlying purpose is to understand how things work behind the scenes, and cover one of the fundamental pillars used in modern JS frameworks such as Angular, React and Vue. So the example itself is not that difficult to achieve, but the concept is what is important.

Heads-up: In this example we use the document interface to access the DOM tree, but as Marko mentioned in the comment section, we can use another powerful interface named documentFragment . It’s a lightweight version of document that prevents layout recalculation and improves the performance when dealing with large amounts of DOM manipulation.

Not only is using DocumentFragments to append about 2700 times faster than appending with innerHTML, but it also keeps the recalculation, painting and layout to a minimum, source .

This article focuses on document interface for two reasons, (1) we are dealing with few elements, and (2) its a familiar interface among developers.

If you want to become a better web developer, start your own business, teach others, or improve your development skills, I’ll be posting weekly tips and tricks on the latest web development languages.

Here’s what we’ll address

Create a list of bookmarks, the javascript part, create a new bookmark.

Show list of bookmarks

In this example, we are going to create a list of bookmarks, append bookmarks to parent element and then present it in HTML using plain JavaScript.

The starting point is an index.html file that consist of a div element with an ID of bookmarks . The ID is an important and necessary factor in order to locate the element so that we can manipulate it.

The ID is case-sensitive string which is unique within the document; only one element may have any given ID, source .

Since this is a small example, we’ve put the JS code in one file index.js . But in terms of best practice, we would separate behaviour by using classes and methods. The code for this example can be found here .

In order to create a collection of bookmarks, we’ll need a placeholder (an array). This allows us to further use array features like push , pop and shift to manipulation data. But in this example, we’ll mainly focus on the push feature for creating new bookmarks.

We’ve also defined few const variables such as childElement , appendChildElement and parentElement to make the code readable.

So the benefit of the bookmarks array is to create objects (a state of information), which we can chain with these functional JS methods like filter() , map() , reduce() , for...of and some() and so forth.

I’ve written an article that covers these useful and important methods for devs that want to improve their skills in web dev, check out .

Now that we have an empty array, next step is to create a bookmark object with property name URL . We do this by using the push method which is used to add a new object when dealing with arrays. Notice that we use curly brackets {} to inform JS that this is an object.

There is a saying among web devs that everything in JS is an object, I haven’t really tested this myth, but I cannot quite disagree either.

So what is an object?

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics. Read more .

Alright, so back to the code, in order to add objects as mentioned earlier, we do something like this. Notice the push method we’ve chained to the bookmarks array.

How to access the bookmarks element

Now that we have a list of bookmarks (objects), we still have couple of steps left before we can present the results in HTML.

Currently, this is what we have.

And this is the end result we want to achieve. So the question is, what method can we use to access the parent element in order to add/append child elements?

JS ecosystem provides multiple of ways to interact with the DOM tree, lets see which one fits our goal.

Option 1: We can use the method getElementByClassName('.class-name') , but this is mostly used when we want to target multiple/similar elements at once.

Option 2: The other option is use querySelector() or querySelectorAll() . But this is mostly relevant when we are dealing with elements that don’t have an ID or class name.

Option 3: The final option and most commonly one is to use getElementById('id-name') because our element has an ID of bookmarks . So for this example, we’ll be using this one.

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly. Read more .

So to access the HTML element with ID bookmarks , and then access the object later in our application, we assign the object to parentElement variable.

And then if console.log(parentElement) we get an HTMLDivElement object like which means the binding works.

Next step is to show the bookmarks URL on the page.

Since we have a list of 3 bookmarks, we can now iterate by using for...of iterator to perform DOM manipulation separately.

In each iteration, we do.

So if everything works we can either see the URLs on the page, or use the debug tool to see if the elements are added properly.

The elements should be structured like this (use debug tool).

It is important to understand the underlying parts of JS, and how it is used to dynamically interact with the DOM tree. One thing is to use a framework that does all of this for you automatically, another thing is to actually know what happens behind the scenes. In overall, it provides the ability to take critical decisions based on architecture and performance, which is not something most devs really want to focus on. Differences like these allows you to understand the limitation of building web apps, and what is achievable in the end.

A framework usually provides us the ability create components such as <app-product-list></app-product-list> or target an element with a unique ID such as <div id="bookmarks"></div> as we’ve done. In both ways, it is recommended to know how things work, so that you can effectively handle unexpected issues in relation to the DOM tree.

Here are a few articles I’ve written about the web-ecosystem along with personal programming tips and tricks.

You can find me on Medium where I publish on a weekly basis. Or you can follow me on Twitter , where I post relevant web development tips and tricks along with personal stories.

P.S. If you enjoyed this article and want more like these, please clap ❤ and share with friends that may need it, it’s good karma.

More from codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

About Help Terms Privacy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

Software Engineer sharing interesting tech topics

Text to speech

Nick McCullum Headshot

Nick McCullum

Software Developer & Professional Explainer

How to Create HTML Elements Using JavaScript

Hey - Nick here! This page is a free excerpt from my $99 course JavaScript Fundamentals.

If you want the full course, click here to sign up and create an account.

I have a 30-day satisfaction guarantee, so there's no risk (and a ton of upside!) in signing up for this course and leveling up your JavaScript developer skills today!

In this tutorial, you will learn how to create HTML elements using JavaScript.

Table of Contents

You can skip to a specific section of this JavaScript tutorial using the table of contents below:

How to Add a New HTML Element to a Page Using JavaScript

The javascript insertadjacentelement method, adding longer chunks of html to a page using javascript, final thoughts.

There are a few different methods that can be used to create new HTML elements using JavaScript.

The main way is using the document.createElement method. This method takes a single argument - the type of HTML element that you are trying to create.

As an example, here is how we could use the createElement method to generate an HTML <p> tag and assign this new tag to a variable called paragraph :

Note that although we have created the new <p> tag, we have not yet placed it anywhere on our page. This means that our page's appearance will remain unchanged.

This <p> tag also contains no text and does not have any styling associated with it. Let's add some text and apply the red-font class to this using the methods we learned earlier in this course.

First, let's change the value of the textContent attribute of the paragraph object:

Second, we can add the red-font class by calling the add method on the classList attribute:

Here's a summary of everything we've done so far:

Now that we have created and styled our HTML element, it's time to add it to our page.

We can add our newly-created HTML element to our page by calling the appendChild element on the document.body object.

The document.body object is an easy way to select the DOM while using JavaScript, and the appendChild method allows us to add new elements to the DOM. We will pass the paragraph variable into the appendChild method to tell JavaScript to add our new HTML element to the page.

You will notice that a new red paragraph with the text This is the first HTML element that we created using JavaScript! appears at the bottom of the page. Nice!

It's important to understand the location of element injections when using the appendChild method. To be more specific, the appendChild method adds a new element to the end of an existing tag in JavaScript.

When you call it on document.body , it naturally adds the element to the end of the page. You can also call the appendChild on other types of HTML tags, such as <div> tags or <span> tags.

In the next section, we will learn about a different JavaScript method that provides more flexibility for HTML injection using JavaScript.

Earlier in this course, we saw the insertAjacentText method as a tool for adding text to an existing HTML element. JavaScript also includes a similar method called insertAdjacentElement that provides similar functionality for HTML elements.

The insertAdjacentElement method takes two arguments: position and element .

The position argument specifies where the new element should be inserted relative to the parent object, and has four possible values:

The element argument is the element you'd like to inject into your page.

Let's consider an example of how to use the insertAdjacentElement method. Specifically, let's add a new <h1> title to our page that says "This is Nick's example index.html file" . This header can be placed at the very beginning of our index.html file:

This technique is useful for adding an individual HTML element to a page, but can become cumbersome when adding multiple elements. You would have to use the createElement and insertAdjacentElement methods for each element you're adding, which would create a very long script.js file.

Fortunately, there is a better way. In the next section of this tutorial, you will learn how to add longer chunks of HTML to a page using JavaScript.

Earlier in this course, we introduced the ``` character - often called the 'backtick' - as one way to create JavaScript strings . These backticks are also excellent candidates for injecting chunks of HTML into your webpage.

To do this, we first need to chose a container for the HTML that we are injecting into the website. We will specifically be using the <div> element that holds the class of container . We can select this HTML element with the following code:

Next, let's specify what HTML code we would like to inject into the page. Let's keep things simple and add a few paragraph tags:

Now it's time to inject these <p> tags into the <div> element. To do this, we use the innerHTML attribute of the container object that we created using the querySelector method.

Here's the code:

There are a few important things you should understand about this code block:

The use of backticks in this code is important for two reasons.

First, the backticks allow us to space the HTML code out over multiple lines. While the code would still function properly if it were all on the same line, spacing the HTML over multiple lines (the same way that it appears in the DOM) makes it much more readable.

Second, the use of backticks allows us to interpolate outside variables into the HTML, which crates many fascinating possibilities.

Here is a rudimentary example that has the same functionality as our previous code block but demonstrates the usefulness of string interpolation with HTML:

In this tutorial, you learned how to create new HTML elements using JavaScript.

Here is a brief summary of what we covered:

// Tutorial //

How to add javascript to html.

Default avatar

By Lisa Tagliaferri

How To Add JavaScript to HTML

Introduction

JavaScript, also abbreviated to JS, is a programming language used in web development. As one of the core technologies of the web alongside HTML and CSS, JavaScript is used to make webpages interactive and to build web apps. Modern web browsers, which adhere to common display standards, support JavaScript through built-in engines without the need for additional plugins.

When working with files for the web, JavaScript needs to be loaded and run alongside HTML markup. This can be done either inline within an HTML document or in a separate file that the browser will download alongside the HTML document.

This tutorial will go over how to incorporate JavaScript into your web files, both inline into an HTML document and as a separate file.

Adding JavaScript into an HTML Document

You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code.

The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.

Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.

However, if your script needs to run at a certain point within a page’s layout — like when using document.write to generate content — you should put it at the point where it should be called, usually within the <body> section.

Let’s consider the following blank HTML document with a browser title of Today's Date :

Right now, this file only contains HTML markup. Let’s say we would like to add the following JavaScript code to the document:

This will enable the webpage to display an alert with the current date regardless of when the user loads the site.

In order to achieve this, we will add a <script> tag along with some JavaScript code into the HTML file.

To begin with, we’ll add the JavaScript code between the <head> tags, signalling the browser to run the JavaScript script before loading in the rest of the page. We can add the JavaScript below the <title> tags, for instance, as shown below:

Once you load the page, you will receive an alert similar to this:

JavaScript Alert Example

If we were modifying what is shown in the body of the HTML, we would need to implement that after the <head> section so that it displays on the page, as in the example below:

The output for the above HTML document loaded through a web browser would look similar to the following:

JavaScript Date Example

Scripts that are small or that run only on one page can work fine within an HTML file, but for larger scripts or scripts that will be used on many pages, it is not a very effective solution because including it can become unwieldy or difficult to read and understand. In the next section, we’ll go over how to handle a separate JavaScript file in your HTML document.

Working with a Separate JavaScript File

In order to accommodate larger scripts or scripts that will be used across several pages, JavaScript code generally lives in one or more js files that are referenced within HTML documents, similarly to how external assets like CSS are referenced.

The benefits of using a separate JavaScript file include:

To demonstrate how to connect a JavaScript document to an HTML document, let’s create a small web project. It will consist of script.js in the js/ directory, style.css in the css/ directory, and a main index.html in the root of the project.

We can start with our previous HTML template from the section above:

Now, let’s move our JavaScript code that will show the date as an <h1> header to the script.js file:

We can add a reference to this script to the <body> section, with the following line of code:

The <script> tag is pointing to the script.js file in the js/ directory of our web project.

Let’s consider this line in the context of our HTML file, in this case, within the <body> section:

Finally, let’s also edit the style.css file by adding a background color and style to the <h1> header:

We can reference that CSS file within the <head> section of our HTML document:

Now, with the JavaScript and CSS in place we can load the index.html page into the web browser of our choice. We should see a page that looks similar to the following:

JavaScript Date with CSS Example

Now that we’ve placed the JavaScript in a file, we can call it in the same way from additional web pages and update them all in a single location

This tutorial went over how to incorporate JavaScript into your web files, both inline into an HTML document and as a separate .js file.

From here, you can learn how to work with the JavaScript Developer Console and how to write comments in JavaScript .

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers - for free! DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Learn more here

Tutorial Series: How To Code in JavaScript

JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.

Still looking for an answer?

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Very nice intro, thanks!

gentle introduction on how javascript and css work with html- foundational concepts gently introduced. Thank you!

Pensei que não estava funcionando bem, mas foi por erro meu na hora de adicionar o código, já está funcionando no meu blog alcir.net . Obrigado !

This comment has been deleted

Thank you very much for this tutorial! It is very clear and simple explained even for a newbie like me :)

I was hoping to find the bit “how to” as i needed to add a tag to all my html pages on the site…sounds like a bulk operation and was hoping to find that info here…but perhaps this was the wrong place …

Creative Commons

Popular Topics

Try DigitalOcean for free

Join the tech talk.

Please complete your information!

IMAGES

  1. How to create HTML Form dynamically using JavaScript (Part-26)

    how to create html javascript

  2. What Is JavaScript? Dynamic Web Sites- Linnet's How To

    how to create html javascript

  3. 39 How To Create A Login Page In Html Using Javascript

    how to create html javascript

  4. How To Create Html File Using Javascript

    how to create html javascript

  5. JavaScript in Practice: Create dynamic buttons with JavaScript, HTML, and CSS

    how to create html javascript

  6. 2 Use external Javascript FIle

    how to create html javascript

VIDEO

  1. Intro to HTML, CSS and JavaScript

  2. Javascript Class 001

  3. Learn Web development using HTML, CSS, JavaScript in 40 minutes

  4. How to Use JavaScript and CSS on a Website?

  5. How To Run HTML code in Android| Create HTML page from Android mobile

  6. HTML CSS Javascript Website

COMMENTS

  1. JavaScript HTML DOM Elements (Nodes)

    To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element. Example. <div id="div1"> <p

  2. 3 Ways To Create HTML Element In JavaScript

    Create a div HTML Element in JavaScript by calling the createElement() method on the document object. This method takes an argument which will

  3. 3 Easy Ways to Generate HTML with JavaScript

    1. Build HTML Element Objects ... We're going to start off strong. This technique involves creating DOM elements using document.createElement(...)

  4. The Best Way to Create HTML Elements with JavaScript?

    In today's video I'll be showing you my favourite way to generate HTML elements using JavaScript.This technique allows you to pass in an

  5. Document.createElement()

    In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName

  6. How to add a new element to HTML DOM in JavaScript

    Step 1 − To insert an element into HTML DOM, firstly, we need to create an element and append to HTML DOM. The document.createElement() is used

  7. Dynamically creating HTML elements using Javascript?

    var tree = document.createDocumentFragment(); var link = document.createElement("a"); link.setAttribute("id", "id1"); link.setAttribute("href"

  8. Learn how to dynamically create HTML elements with plain JavaScript

    The starting point is an index.html file that consist of a div element with an ID of bookmarks . The ID is an important and necessary factor in

  9. How to Create HTML Elements Using JavaScript

    There are a few different methods that can be used to create new HTML elements using JavaScript. The main way is using the document.createElement method. This

  10. How To Add JavaScript to HTML

    You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag