• JavaScript Home
  • ▼JavaScript Exercises
  • Exercises Home
  • Fundamental(ES6) Part-I
  • Fundamental(ES6) Part-II
  • Error Handling
  • Conditional statements and loops
  • Event Handling
  • Asynchronous
  • Object-Oriented Programming
  • Linked List
  • String/Text
  • Bit Manipulation
  • Validation with Regular expression
  • Validation without Regular expression
  • Sorting Algorithm
  • Searching Algorithm
  • ..More to come..

JavaScript DOM - Exercises, Practice, Solution

Javascript dom [13 exercises with solution].

[ An editor is available at the bottom of the page to write and execute the scripts.   Go to the editor ]

Clicking on the button the font, font size, and color of the paragraph text will be changed. Click me to see the solution

2. Write a JavaScript function to get the values of First and Last names of the following form. Sample HTML file :

Click me to see the solution

3. Write a JavaScript program to set paragraph background color.

4. Here is a sample HTML file with a submit button. Write a JavaScript function to get the value of the href, hreflang, rel, target, and type attributes of the specified link.

5. Write a JavaScript function to add rows to a table. Sample HTML file :

6. Write a JavaScript function that accepts a row, column (to identify a particular cell) and a string to update the cell's contents. Sample HTML file :

7. Write a JavaScript function to create a table, accept row and column numbers, and input row-column numbers as cell content (e.g. Row-0 Column-0). Sample HTML file :

8. Write a JavaScript program to remove items from a drop-down list. Sample HTML file :

9. Write a JavaScript program to count and display dropdown list items in an alert window. Sample HTML file :

10. Write a JavaScript program to calculate sphere volume. Sample Output of the form :

volume sphere html form

11. Write a JavaScript program to display a random image (clicking on a button) from the following list. Sample Image information :

"http://farm4.staticflickr.com/3691/11268502654_f28f05966c_m.jpg", width: "240", height: "160" "http://farm1.staticflickr.com/33/45336904_1aef569b30_n.jpg", width: "320", height: "195" "http://farm6.staticflickr.com/5211/5384592886_80a512e2c9.jpg", width: "500", height: "343"

12. Write a JavaScript program to highlight the bold words of the following paragraph, on mouse over a certain link. Sample link and text : [ On mouse over here bold words of the following paragraph will be highlighted ] We have just started this section for the users ( beginner to intermediate) who want to work with various JavaScript problems and write scripts online to test their JavaScript skill . Click me to see the solution

More to Come !

* To run the code mouse over on Result panel and click on 'RERUN' button. *

See the Pen javascript-common-editor by w3resource ( @w3resource ) on CodePen .

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-dom-exercises.php

  • Weekly Trends and Language Statistics

DEV Community

DEV Community

James Bubb

Posted on Jan 29, 2020

JavaScript DOM Practice Exercises For Beginners

This week on the YouTube channel I run I posted a few videos on completing practical JavaScript exercises all focused on manipulating the DOM.

I thought it would be a good way of applying your JavaScript skills, to more ‘real-life’ situations.

Here’s a sample of some of the exercises...

You can check out the setup for the exercises on their respective Codepen pages and I give an example solution (not saying it’s the best way!) for each exercise in the tutorial videos.

Video 1 : Exercise 1

See the code and full exercise on Codepen

Highlight all of the words over 8 characters long in the paragraph text (with a yellow background for example)

Alt Text

In this exercise, I was asking users to extract the contents of a paragraph tag and then put a highlighted background behind words that are longer than 8 characters. It’s always tricky to work determine where a word starts and ends in a string (multiple spaces, symbols etc.) but because we only needed to apply the rule to words over 8 characters we can get away with a relaxed approach.

How would you go about solving this one?

Video 1 : Exercise 5

Replace all question marks (?) with thinking faces (🤔) and exclamation marks (!) with astonished faces (😲)

Alt Text

This one was, hopefully, quite straightforward although it did get a bit more complicated as a previous exercise had created multiple paragraph tags on the page. It’s a good bit of string manipulation practice too.

Got your own solution for this?

Video 2 : Exercise 2

Add a required validation to each input that shows an error message next to the entry if it does not have any text entered.

Alt Text

So in Video 2 we were working with a simple Bootstrap based registration form and this exercise was based around setting up some form validation. I was looking for a simple solution to this one but it was complicated managing multiple instances of errors (like them stacking on top of each other when the validation hasn’t been met). So the solution I provided was a bit messy, but did the trick.

Can you solve this with a simpler solution?

Video 3 : Exercise 2

To make the ordering of the plans more logical, using JavaScript, move the basic plan to be before (to the left) of the pro plan.

Alt Text

In Video 3 we had a simple pricing table with two products, a basic and pro plan and this was an exercise in moving elements around in the DOM. There’s a simple solution to this using CSS but can you achieve this using JavaScript?

Video 3 : Exercise 3

To make the Pro plan have a stronger call to action, update the current 'Get started' button to be blue (#007bff) with white text and have the text 'Buy Now'

Alt Text

Normally you would update your styles directly in your CSS (or it’s pre-processor) but this exercise was asking you to do this with JavaScript and there’s a shortcut you can take if you know your Bootstrap classes.

If you check out the exercises then I hope you find them useful for practicing your JavaScript skills. If you do then consider subscribing to the Junior Developer Central channel and don’t forget to leave a comment with your own solutions to the exercises.

Top comments (0)

pic

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

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

yashnarkhedkar profile image

How to Convert PDF Pages to Images in Node.js

yashnarkhedkar - Sep 16

bhataasim profile image

Why do React components need to start with capital letters?

Bhat Aasim - Sep 21

mateuscechetto profile image

How to Test Functions That Return Functions in TypeScript with Jest

Mateus Cechetto - Sep 15

rohan_sharma profile image

Fly with AI Copilots using CopilotKit 🪁

Rohan Sharma - Sep 22

DEV Community

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

The Modern JavaScript DOM Cheat Sheet

This article provides a comprehensive cheat sheet for modern JavaScript DOM, covering a wide range of methods and properties that you can use to interact with the Document Object Model in your web applications.

Selecting Elements

  • document.querySelector(selector) – selects the first element that matches the CSS selector.
  • document.querySelectorAll(selector) – selects all elements that match the CSS selector.
  • document.getElementById(id) – selects the element with the specified ID.
  • document.getElementsByClassName(className) – selects all elements with the specified class name.
  • document.getElementsByTagName(tagName) – selects all elements with the specified tag name.
  • element.matches(selector) – returns a Boolean indicating whether the element matches the specified CSS selector.

Creating and Modifying Elements

  • document.createElement(tagName) – creates a new element with the specified tag name.
  • element.appendChild(childElement) – appends a child element to the end of the parent element.
  • element.insertBefore(newElement, referenceElement) – inserts a new element before the specified reference element.
  • element.setAttribute(name, value) – sets the value of the specified attribute for an element.
  • element.removeAttribute(name) – removes the specified attribute from an element.
  • element.innerHTML – sets or gets the HTML content of an element.
  • element.textContent – sets or gets the text content of an element.
  • element.insertAdjacentHTML(position, htmlString) – inserts HTML into the specified position relative to the element.
  • element.insertAdjacentText(position, text) – inserts text into the specified position relative to the element.

Styling Elements

  • element.style.property = value – sets a CSS property for an element.
  • element.classList.add(className) – adds a class to an element.
  • element.classList.remove(className) – removes a class from an element.
  • element.classList.toggle(className) – toggles a class on or off for an element.
  • element.classList.contains(className) – returns a Boolean value indicating whether an element has a specified class.
  • window.getComputedStyle(element) – returns the computed style of an element.

Event Handling

  • element.addEventListener(event, function) – adds an event listener to an element.
  • element.removeEventListener(event, function) – removes an event listener from an element.
  • event.preventDefault() – prevents the default action of an event.
  • event.stopPropagation() – stops the propagation of an event to parent elements.
  • event.target – returns the element that triggered the event.
  • event.currentTarget – returns the element to which the event listener is attached.
  • event.type – returns the type of the event.
  • event.key – returns the key that was pressed (for keyboard events).
  • event.keyCode – returns the Unicode value of the key that was pressed (for keyboard events).
  • element.parentNode – returns the parent node of an element.
  • element.childNodes – returns a collection of all child nodes of an element.
  • element.firstChild – returns the first child node of an element.
  • element.lastChild – returns the last child node of an element.
  • element.previousSibling – returns the previous sibling node of an element.
  • element.nextSibling – returns the next sibling node of an element.
  • element.parentElement – returns the parent element of an element (excluding text and comment nodes).
  • element.children – returns a collection of all child elements of an element (excluding text and comment nodes).

Attributes and Properties

  • element.getAttribute(name) – returns the value of the specified attribute for an element.
  • element.propertyName – sets or gets the value of a property for an element.
  • element.dataset – returns a DOMStringMap containing all the custom data attributes of an element.
  • element.hasAttribute(name) – returns a Boolean indicating whether an element has the specified attribute.
  • element.propertyName = value – sets the value of a property for an element.

DOM Manipulation

  • document.createDocumentFragment() – creates a new empty document fragment.
  • element.cloneNode(deep) – creates a clone of an element, optionally cloning its child nodes.
  • element.removeChild(childElement) – removes a child element from the parent element.
  • element.replaceChild(newElement, oldElement) – replaces an old child element with a new child element.
  • element.contains(childElement) – returns a Boolean indicating whether an element is a descendant of another element.
  • document.importNode(node, deep) – imports a node from another document into the current document.

Performance Optimization

  • requestAnimationFrame(callback) – schedules a function to run the next time the browser renders a frame, usually at 60 frames per second.
  • window.performance.mark(name) – creates a performance mark with the specified name.
  • window.performance.measure(name, startMark, endMark) – creates a performance measure with the specified name, using the specified start and end marks.
  • element.getBoundingClientRect() – returns a DOMRect object containing the size and position of an element.
  • element.offsetWidth – returns the width of an element, including padding and border but not margin.
  • element.offsetHeight – returns the height of an element, including padding and border but not margin.
  • element.offsetLeft – returns the distance between an element’s left edge and its offset parent’s left edge.
  • element.offsetTop – returns the distance between an element’s top edge and its offset parent’s top edge.

More Methods and Properties

  • document.cookie – sets or gets the cookies associated with the current document.
  • document.title – sets or gets the title of the current document.
  • window.location – sets or gets the current URL of the window.
  • window.navigator – returns an object containing information about the user’s browser and operating system.
  • window.alert(message) – displays an alert dialog with the specified message.
  • window.prompt(message, defaultValue) – displays a prompt dialog with the specified message and default value.

The above is the most concise information about the DOM in modern JavaScript. If you want to see more detailed guides and specific examples, keep reading the tutorials in this series, such as:

  • JavaScript: Set HTML lang attribute programmatically
  • JavaScript: Detect a click outside an HTML element

Happy coding and have a nice day!

Next Article: JavaScript: Set HTML lang attribute programmatically

Series: JavaScript: Document Object Model Tutorials

Related Articles

  • JavaScript: Press ESC to exit fullscreen mode (2 examples)
  • Can JavaScript programmatically bookmark a page? (If not, what are alternatives)
  • Dynamic Import in JavaScript: Tutorial & Examples (ES2020+)
  • JavaScript: How to implement auto-save form
  • JavaScript: Disable a Button After a Click for N Seconds
  • JavaScript: Detect when a Div goes into viewport
  • JavaScript Promise.any() method (basic and advanced examples)
  • Using logical nullish assignment in JavaScript (with examples)
  • Understanding WeakRef in JavaScript (with examples)
  • JavaScript Numeric Separators: Basic and Advanced Examples
  • JavaScript: How to Identify Mode(s) of an Array (3 Approaches)
  • JavaScript: Using AggregateError to Handle Exceptions

Search tutorials, examples, and resources

  • PHP programming
  • Symfony & Doctrine
  • Laravel & Eloquent
  • Tailwind CSS
  • Sequelize.js
  • Mongoose.js

DOM Manipulation and Events

Foundations course, introduction.

One of the most unique and useful abilities of JavaScript is its ability to manipulate the DOM. But what is the DOM, and how do we go about changing it? Let’s jump right in…

Lesson overview

This section contains a general overview of topics that you will learn in this lesson.

  • Explain what the DOM is in relation to a webpage.
  • Explain the difference between a “node” and an “element”.
  • Explain how to target nodes with “selectors”.
  • Explain the basic methods for finding, adding, removing, and altering DOM nodes.
  • Explain the difference between a “NodeList” and an “array of nodes”.
  • Explain what “bubbling” is and how it works.

Document Object Model

The DOM (or Document Object Model) is a tree-like representation of the contents of a webpage - a tree of “nodes” with different relationships depending on how they’re arranged in the HTML document. There are many types of nodes, most of which are not commonly used. In this lesson we will be focusing on “element” nodes which are primarily used for manipulating the DOM.

In the above example, the <div class="display"></div> is a “child” of <div id="container"></div> and a “sibling” to <div class="controls"></div> . Think of it like a family tree. <div id="container"></div> is a parent , with its children on the next level, each on their own “branch”.

Targeting nodes with selectors

When working with the DOM, you use “selectors” to target the nodes you want to work with. You can use a combination of CSS-style selectors and relationship properties to target the nodes you want. Let’s start with CSS-style selectors. In the above example, you could use the following selectors to refer to <div class="display"></div> :

  • div.display
  • #container > .display
  • div#container > div.display

You can also use relational selectors (i.e., firstElementChild or lastElementChild , etc.) with special properties owned by the nodes.

So you’re identifying a certain node based on its relationships to the nodes around it.

DOM methods

When your HTML code is parsed by a web browser, it is converted to the DOM, as was mentioned above. One of the primary differences is that these nodes are JavaScript objects that have many properties and methods attached to them. These properties and methods are the primary tools we are going to use to manipulate our webpage with JavaScript.

Query selectors

  • element.querySelector(selector) - returns a reference to the first match of selector .
  • element.querySelectorAll(selectors) - returns a “NodeList” containing references to all of the matches of the selectors .

It’s important to remember that when using querySelectorAll, the return value is not an array. It looks like an array, and it somewhat acts like an array, but it’s really a “NodeList”. The big distinction is that several array methods are missing from NodeLists. One solution, if problems arise, is to convert the NodeList into an array. You can do this with Array.from() or the spread operator.

Element creation

  • document.createElement(tagName, [options]) - creates a new element of tag type tagName. [options] in this case means you can add some optional parameters to the function. Don’t worry about these at this point.

This function does NOT put your new element into the DOM - it creates it in memory. This is so that you can manipulate the element (by adding styles, classes, ids, text, etc.) before placing it on the page. You can place the element into the DOM with one of the following methods.

Append elements

  • parentNode.appendChild(childNode) - appends childNode as the last child of parentNode .
  • parentNode.insertBefore(newNode, referenceNode) - inserts newNode into parentNode before referenceNode .

Remove elements

  • parentNode.removeChild(child) - removes child from parentNode on the DOM and returns a reference to child .

Altering elements

When you have a reference to an element, you can use that reference to alter the element’s own properties. This allows you to do many useful alterations, like adding, removing, or altering attributes, changing classes, adding inline style information, and more.

Adding inline style

When accessing a kebab-cased CSS property like background-color with JS, you will need to either use camelCase with dot notation or bracket notation. When using bracket notation, you can use either camelCase or kebab-case, but the property name must be a string.

Editing attributes

See MDN’s section on HTML Attributes for more information on available attributes.

Working with classes

It is often standard (and cleaner) to toggle a CSS style rather than adding and removing inline CSS.

Adding text content

Adding html content.

Note that using textContent is preferred over innerHTML for adding text, as innerHTML should be used sparingly to avoid potential security risks. To understand the dangers of using innerHTML, watch this video about preventing the most common cross-site scripting attack .

Let’s take a minute to review what we’ve covered and give you a chance to practice this stuff before moving on. Check out this example of creating and appending a DOM element to a webpage.

In the JavaScript file, first we get a reference to the container div that already exists in our HTML. Then we create a new div and store it in the variable content . We add a class and some text to the content div and finally append that div to container . After the JavaScript code is run, our DOM tree will look like this:

Keep in mind that the JavaScript does not alter your HTML, but the DOM - your HTML file will look the same, but the JavaScript changes what the browser renders.

Your JavaScript, for the most part, is run whenever the JS file is run or when the script tag is encountered in the HTML. If you are including your JavaScript at the top of your file, many of these DOM manipulation methods will not work because the JS code is being run before the nodes are created in the DOM. The simplest way to fix this is to include your JavaScript at the bottom of your HTML file so that it gets run after the DOM nodes are parsed and created.

Alternatively, you can link the JavaScript file in the <head> of your HTML document. Use the <script> tag with the src attribute containing the path to the JS file, and include the defer keyword to load the file after the HTML is parsed, as such:

Find out more about the defer attribute for script tags .

Copy the example above into files on your own computer. To make it work, you’ll need to supply the rest of the HTML skeleton and either link your JavaScript file or put the JavaScript into a script tag on the page. Make sure everything is working before moving on!

Add the following elements to the container using ONLY JavaScript and the DOM methods shown above:

  • a <p> with red text that says “Hey I’m red!”
  • an <h3> with blue text that says “I’m a blue h3!”
  • another <h1> that says “I’m in a div”
  • a <p> that says “ME TOO!”
  • Hint for this one: after creating the <div> with createElement, append the <h1> and <p> to it before adding it to the container.

Now that we have a handle on manipulating the DOM with JavaScript, the next step is learning how to make that happen dynamically or on demand! Events are how you make that magic happen on your pages. Events are actions that occur on your webpage, such as mouse-clicks or key-presses. Using JavaScript, we can make our webpage listen to and react to these events.

There are three primary ways to go about this:

  • You can specify function attributes directly on your HTML elements.
  • You can set properties in the form of on<eventType> , such as onclick or onmousedown , on the DOM nodes in your JavaScript.
  • You can attach event listeners to the DOM nodes in your JavaScript.

Event listeners are definitely the preferred method, but you will regularly see the others in use, so we’re going to cover all three.

We’re going to create three buttons that all alert “Hello World” when clicked. Try them all out using your own HTML file or using something like CodePen .

This solution is less than ideal because we’re cluttering our HTML with JavaScript. Also, we can only set one “onclick” property per DOM element, so we’re unable to run multiple separate functions in response to a click event using this method.

If you need to review the arrow syntax () => , check this article about arrow functions .

This is a little better. We’ve moved the JS out of the HTML and into a JS file, but we still have the problem that a DOM element can only have one “onclick” property.

Now, we maintain separation of concerns, and we also allow multiple event listeners if the need arises. Method 3 is much more flexible and powerful, though it is a bit more complex to set up.

Note that all three of these methods can be used with named functions like so:

Using named functions can clean up your code considerably, and is a really good idea if the function is something that you are going to want to do in multiple places.

With all three methods, we can access more information about the event by passing a parameter to the function that we are calling. Try this out on your own machine:

When we pass in alertFunction or function (e) {...} as an argument to addEventListener , we call this a callback . A callback is simply a function that is passed into another function as an argument.

The e parameter in that callback function contains an object that references the event itself. Within that object you have access to many useful properties and methods (functions that live inside an object) such as which mouse button or key was pressed, or information about the event’s target - the DOM node that was clicked.

and now this:

Pretty cool, eh?

Attaching listeners to groups of nodes

This might seem like a lot of code if you’re attaching lots of similar event listeners to many elements. There are a few ways to go about doing that more efficiently. We learned above that we can get a NodeList of all of the items matching a specific selector with querySelectorAll('selector') . In order to add a listener to each of them, we need to iterate through the whole list, like so:

This is just the tip of the iceberg when it comes to DOM manipulation and event handling, but it’s enough to get you started with some exercises. In our examples so far, we have been using the ‘click’ event exclusively, but there are many more available to you.

Some useful events include:

You can find a more complete list with explanations of each event on W3Schools JavaScript Event Reference page .

Manipulating web pages is the primary benefit of the JavaScript language! These techniques are things that you are likely to be messing with every day as a front-end developer, so let’s practice!

  • Complete MDN’s Active Learning sections on DOM manipulation to test your skills!

Read the following sections from JavaScript Tutorial’s series on the DOM to get a broader idea of how events can be used in your pages. Note that some of the methods like getElementById are older and see less use today.

As you read, remember that the general ideas can be applied to any event, not only the ones used in examples - but information specific to a certain event type can always be found by checking documentation.

  • JavaScript events
  • Page load events
  • Mouse events
  • Keyboard events
  • Event delegation
  • The dispatchEvent method
  • Custom events

Knowledge check

The following questions are an opportunity to reflect on key topics in this lesson. If you can’t answer a question, click on it to review the material, but keep in mind you are not expected to memorize or master this knowledge.

  • What is the DOM?
  • How do you target the nodes you want to work with?
  • How do you create an element in the DOM?
  • How do you add an element to the DOM?
  • How do you remove an element from the DOM?
  • How can you alter an element in the DOM?
  • When adding text to a DOM element, should you use textContent or innerHTML? Why?
  • Where should you include your JavaScript tag in your HTML file when working with DOM nodes?
  • How do “events” and “listeners” work?
  • What are three ways to use events in your code?
  • Why are event listeners the preferred way to handle events?
  • What are the benefits of using named functions in your listeners?
  • How do you attach listeners to groups of nodes?
  • What is the difference between the return values of querySelector and querySelectorAll ?
  • What does a “NodeList” contain?
  • Explain the difference between “capture” and “bubbling”.

Additional resources

This section contains helpful links to related content. It isn’t required, so consider it supplemental.

  • Eloquent JS - DOM
  • Eloquent JS - Handling Events
  • DOM Enlightenment
  • Plain JavaScript is a reference of JavaScript code snippets and explanations involving the DOM, as well as other aspects of JS. If you’ve already learned jQuery, it will help you figure out how to do things without it.
  • This W3Schools article offers easy-to-understand lessons on the DOM.
  • JS DOM Crash Course is an extensive and well explained 4 part video series on the DOM by Traversy Media.
  • Understanding The Dom is an aptly named article-based tutorial series by DigitalOcean.
  • Introduction to events by MDN covers the same topics you learned in this lesson on events.
  • Wes Bos’s Drumkit JavaScript30 program reinforces the content covered in the assignment. In the video you will notice that a deprecated keycode keyboard event is used, replace it with the recommended code keyboard event and replace the data-key tags accordingly.
  • Event Capture, Propagation and Bubbling video from Wes Bos’s JavaScript30 program.
  • Understanding Callbacks in JavaScript for a more in-depth understanding of callbacks.

Support us!

The odin project is funded by the community. join us in empowering learners around the globe by supporting the odin project.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

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.

Get early access and see previews of new features.

How can I add a class to a DOM element in JavaScript?

How do I add a class for the div ?

Peter Mortensen's user avatar

  • 14 Too bad the spec doesn't allow classes to be specified as a parameter to createElement. –  Gaʀʀʏ Commented Dec 20, 2016 at 16:40
  • If you want to add a class without removing other classes , see this answer . –  Michał Perłakowski Commented Mar 14, 2018 at 14:10

12 Answers 12

This answer was written/accepted a long time ago. Since then better, more comprehensive answers with examples have been submitted. You can find them by scrolling down. Below is the original accepted answer preserved for posterity.

Here's more information on MDN: className

Darko's user avatar

  • 7 what about setting multiple class names? –  Simon Commented Apr 21, 2014 at 21:57
  • 8 @Sponge new_row.className = "aClassName1 aClassName2"; its just an attribute, you can assign any string you like, even if it makes for invalid html –  Darko Commented Apr 29, 2014 at 9:47
  • 42 I also would recommend new_row.classList.add('aClassName'); as you can then add multiple class names –  StevenTsooo Commented Dec 28, 2014 at 23:09
  • @StevenTsooo Note that classList is unsupported in IE9 or below. –  dayuloli Commented Jan 7, 2015 at 16:19
  • Is there a way to create an element with a classname in one line of code - and still get a reference to the element? for example: myEL = document.createElement('div').addClass('yo')' will not work. –  Kokodoko Commented Dec 30, 2015 at 12:28

Use the .classList.add() method:

const element = document.querySelector('div.foo'); element.classList.add('bar'); console.log(element.className); <div class="foo"></div>

This method is better than overwriting the className property, because it doesn't remove other classes and doesn't add the class if the element already has it.

You can also toggle or remove classes using element.classList (see the MDN documentation ).

Michał Perłakowski's user avatar

  • Correct. But this doesn't really matter in the case of the OP, as they are asking how to add a class to a newly created element. –  Jules Colle Commented Nov 29, 2022 at 19:08

3 ways to add a class to a DOM element in JavaScript

There are multiple ways of doing this. I will show you three ways to add classes and clarify some benefits of each way.

You can use any given method to add a class to your element, another way to check for, change or remove them.

  • The className way - Simple way to add a single or multiple classes and remove or change all classes.
  • The classList way - The way to manipulate classes; add, change or remove a single or multiple classes at the same time. They can easily be changed at any time in your code.
  • The DOM way - When writing code according to the DOM model, this gives a cleaner code and functions similar to the className way.

The className way

This is the simple way, storing all classes in a string. The string can easily be changed or appended.

If an element has a single class , checking for it is simple:

Removing all classes or changing them is very easy

Searching for or removing a single class when multiple classes are used is difficult. You need to split the className string into an array, search them through one by one, remove the one you need and add all others back to your element. The classList way addresses this problem and can be used even if the class was set the className way.

The classList way

It is easy to manipulate classes when you need to. You can add, remove or check for them as you wish! It can be used with single or multiple classes.

Removing all classes or changing to a single class is easier done the className way.

The DOM way

If you write code the DOM way, this looks cleaner and stores classes in a string by setting the class attribute.

Checking for a class is simple, when a single class is being used

Checking for or removing a single class when multiple classes are used uses the same approach as the className way. But the classList way is easier to accomplish this and can be used, even if you set it the DOM way.

Hasse Björk's user avatar

Here is working source code using a function approach.

Sunny S.M's user avatar

  • 8 So? It serves as an example, there's nothing wrong with that. –  Carey Commented Dec 27, 2015 at 23:05
  • Re "while created" : Do you mean "while being created" ? Respond by editing your answer , not here in comments. Thanks in advance. –  Peter Mortensen Commented Jan 29, 2020 at 10:04
  • An explanation would be in order. For example, what do you mean by "a function approach" ? Can you elaborate (by editing your answer , not here in comments)? Thanks in advance. –  Peter Mortensen Commented Jan 29, 2020 at 10:07

If doing a lot of element creations, you can create your own basic createElementWithClass function.

Very basic I know, but being able to call the following is less cluttering.

as opposed to a lot of

over and over.

jedensuscg's user avatar

If you want to create multiple elements all with in one method.

function createElement(el, options, listen = [], appendTo){ let element = document.createElement(el); Object.keys(options).forEach(function (k){ element[k] = options[k]; }); if(listen.length > 0){ listen.forEach(function(l){ element.addEventListener(l.event, l.f); }); } appendTo.append(element); } let main = document.getElementById('addHere'); createElement('button', {id: 'myBtn', className: 'btn btn-primary', textContent: 'Add Alert'}, [{ event: 'click', f: function(){ createElement('div', {className: 'alert alert-success mt-2', textContent: 'Working' }, [], main); } }], main); <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ [email protected] /dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <div id="addHere" class="text-center mt-2"></div>

xNaii's user avatar

  • 3 Consider explaining why you posted this, it will help others to learn. –  Thomas Smyth Commented Dec 2, 2017 at 18:48
  • voted up because this is native JavaScript/vanilla JavaScript and does not need any other libraries or frameworks. –  obotezat Commented Nov 8, 2018 at 9:49
  • 1 An explanation would be in order. –  Peter Mortensen Commented Jan 29, 2020 at 10:16

Cross-browser solution

Note: The classList property is not supported in Internet Explorer 9 . The following code will work in all browsers:

Source: how to js add class

Community's user avatar

This will work ;-)

MEDZ's user avatar

  • This is not a good solution as this approach does not work on all browsers. setAttribute is supported by only 60% of browsers in use today. caniuse.com/#search=setAttribute –  Ragas Commented Feb 2, 2020 at 14:32

It is also worth taking a look at:

JoniS's user avatar

  • 1 An explanation would be in order. –  Peter Mortensen Commented Jan 29, 2020 at 10:14

If you want to create a new input field with for example file type:

The output will be: <input type="file" class="w-95 mb-1">

If you want to create a nested tag using JavaScript, the simplest way is with innerHtml :

The output will be:

Mile Mijatović's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

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 and acknowledge you have read our privacy policy .

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

  • The Overflow Blog
  • Where developers feel AI coding tools are working—and where they’re missing...
  • He sold his first company for billions. Now he’s building a better developer...
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • U.S Citizen married to Danish Citizen living in Sweden with active resident card application - Can we travel to Denmark together?
  • Firefox isn't upgraded on Debian: its ESR has 1.5 years old, ensuring it being discarded. How to ask a global upgrade from Debian or Mozilla team?
  • How can the doctor measure out a dose (dissolved in water) of exactly 10% of a tablet?
  • A time-travel short story where the using a time-travel device, its inventor provided an alibi for his future murderer (his wife)
  • Is a private third party allowed to take things to court?
  • If I was ever deported, would it only be to my country of citizenship? Or can I arrange something else?
  • What is the point of "what is the point?" argument in re determinism?
  • According to Trinitarians, how could Jesus (God the Son) be GIVEN life in Himself (John 5:26), if he shares the same essence of being than the Father?
  • Is there a way to have my iPhone register my car which doesn't have carplay, only for the "Car is parked at"-feature?
  • Graphic to fit in Cell Tabularray
  • How can one be compensated for loss caused negligently by someone who dies in the process?
  • In the absence of an agreement addressing the issue, is there any law giving a university copyright in an undergraduate student's class paper?
  • Soldering a thermal fuse. 92°C
  • Bridge in a walled garden
  • I need a temporary hoist and track system to lift a dead chest freezer up through a tight stairwell
  • Figure out which of your friends reveals confidential information to the media!
  • Pulling myself up with a pulley attached to myself
  • Are there individual protons and neutrons in a nucleus?
  • How do I link a heading containing spaces in Markdown?
  • An everyday expression for "to dilute something with two/three/four/etc. times its volume of water"
  • Do all languages distinguish between persons and non-persons?
  • How to align view to uneven face to get straight orientation? (without the need of rolling/rotating view afterwards)
  • US Visa Appointment error: "Your personal details match a profile which already exists in our database"
  • How do Cultivator Colossus and bounce lands interact?

javascript dom assignment

  • HTML Tutorial
  • HTML Exercises
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • DOM Audio/Video
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter

HTML DOM (Document Object Model)

HTML DOM (Document Object Model) is a hierarchical representation of HTML documents. It defines the structure and properties of elements on a webpage, enabling JavaScript to dynamically access, manipulate, and update content, enhancing interactivity and functionality.

Note : It is called a Logical structure because DOM doesn’t specify any relationship between objects. 

Table of Content

  • Why DOM is required?

Structure of DOM

Properties of dom.

  • Methods of Document Object Model

What DOM is not? 

  • Levels of DOM:

What is DOM?

DOM , or Document Object Model , is a programming interface that represents structured documents like HTML and XML as a tree of objects. It defines how to access, manipulate, and modify document elements using scripting languages like JavaScript.

So basically Document Object Model is an API that represents and interacts with HTML or XML documents.

The DOM is a W3C (World Wide Web Consortium) standard and it defines a standard for accessing documents.

The W3C Dom standard is divided into three different parts:

  • Core DOM – standard model for all document types
  • XML DOM – standard model for XML documents
  • HTML DOM – standard model for HTML documents

HTML DOM is a standard object model and programming interface for HTML documents. HTML DOM is a way to represent the webpage in a structured hierarchical way so that it will become easier for programmers and users to glide through the document.

With HTML DOM, we can easily access and manipulate tags, IDs, classes, attributes, or elements of HTML using commands or methods provided by the document object.

Using DOM JavaScript we get access to HTML as well as CSS of the web page and can also modify the behavior of the HTML elements.

Why is DOM Required?

HTML is used to structure the web pages and Javascript is used to add behavior to our web pages. When an HTML file is loaded into the browser, the JavaScript can not understand the HTML document directly. So it interprets and interacts with the Document Object Model (DOM), which is created by the browser based on the HTML document.

DOM is basically the representation of the same HTML document but in a tree-like structure composed of objects. JavaScript can not understand the tags(<h1>H</h1>) in HTML document but can understand object h1 in DOM.

JavaScript interprets DOM easily, using it as a bridge to access and manipulate the elements. DOM Javascript allow access to each of the objects (h1, p, etc) by using different functions.

The Document Object Model (DOM) is essential in web development for several reasons:

  • Dynamic Web Pages: It allows you to create dynamic web pages. It enables the JavaScript to access and manipulate page content, structure, and style dynamically which gives interactive and responsive web experiences, such as updating content without reloading the entire page or responding to user actions instantly.
  • Interactivity: With the DOM, you can respond to user actions (like clicks, inputs, or scrolls) and modify the web page accordingly.
  • Content Updates: When you want to update the content without refreshing the entire page, the DOM enables targeted changes making the web applications more efficient and user-friendly.
  • Cross-Browser Compatibility: Different browsers may render HTML and CSS in different ways. The DOM provides a standardized way to interact with page elements.
  • Single-Page Applications (SPAs): Applications built with frameworks such as React or Angular, heavily rely on the DOM for efficient rendering and updating of content within a single HTML page without reloading the full page.

DOM can be thought of as a Tree or Forest (more than one tree). The term structure model is sometimes used to describe the tree-like representation of a document.  

Each branch of the tree ends in a node, and each node contains objects  Event listeners can be added to nodes and triggered on an occurrence of a given event. One important property of DOM structure models is structural isomorphism : if any two DOM implementations are used to create a representation of the same document, they will create the same structure model, with precisely the same objects and relationships.

Why DOM is called an Object Model?

Documents are modeled using objects, and the model includes not only the structure of a document but also the behavior of a document and the objects of which it is composed like tag elements with attributes in HTML.

Let’s see the properties of the document object that can be accessed and modified by the document object.

properties of DOM flowchart

Representation of the DOM

  • Window Object : Window Object is object of the browser which is always at top of the hierarchy.  It is like an API that is used to set and access all the properties and methods of the browser. It is automatically created by the browser.
  • Document object: When an HTML document is loaded into a window, it becomes a document object. The ‘document’ object has various properties that refer to other objects which allow access to and modification of the content of the web page. If there is a need to access any element in an HTML page, we always start with accessing the ‘document’ object. Document object is property of window object.
  • Form Object: It is represented by form tags.
  • Link Object : It is represented by link tags.
  • Anchor Object : It is represented by a href tags.
  • Form Control Elements: Form can have many control elements such as text fields, buttons, radio buttons, checkboxes, etc.

Methods of Document Object

DOM provides various methods that allows users to interact with and manipulate the document. Some commonly used DOM methods are:

MethodDescription
(“string”)Writes the given string on the document.
Returns the element having the given id value.
Returns all the elements having the given name value.
Returns all the elements having the given tag name.
Returns all the elements having the given class name.

Example: In this example, We use HTML element id to find the DOM HTML element.

getelementbyid() method example output

Getting the HTML element by getElementById() Method

Example : This example describes the representation of the HTML elements in the tree structure.

html elements in tree-like structure

HTML elements in tree-like structure

  • The Document Object Model is not a binary description where it does not define any binary source code in its interfaces.
  • The Document Object Model is not used to describe objects in XML or HTML whereas the DOM describes XML and HTML documents as objects.
  • The Document Object Model is not represented by a set of data structures ; it is an interface that specifies object representation.
  • The Document Object Model does not show the criticality of objects in documents i.e it doesn’t have information about which object in the document is appropriate to the context and which is not.

Levels of DOM

DOM consisted of multiple levels, each representing different aspect of the document.

  • Level 0: Provides a low-level set of interfaces.
  • CORE provides low-level interfaces that can be used to represent any structured document.
  • HTML provides high-level interfaces that can be used to represent HTML documents.
  • CORE2 : extends the functionality of CORE specified by DOM level 1.
  • VIEWS : views allows programs to dynamically access and manipulate the content of the document.
  • EVENTS : Events are scripts that are either executed by the browser when the user reacts to the web page.
  • STYLE : allows programs to dynamically access and manipulate the content of style sheets.
  • TRAVERSAL : This allows programs to dynamically traverse the document.
  • RANGE : This allows programs to dynamically identify a range of content in the document.
  • CORE3 : extends the functionality of CORE specified by DOM level 2.
  • LOAD and SAVE : This allows the program to dynamically load the content of the XML document into the DOM document and save the DOM Document into an XML document by serialization.
  • VALIDATION : This allows the program to dynamically update the content and structure of the document while ensuring the document remains valid.
  • EVENTS : extends the functionality of Events specified by DOM Level 2.
  • XPATH : XPATH is a path language that can be used to access the DOM tree.

Example: This example illustrates the dom-manipulation using getElementById() Method.

manipulating document object using getelementbyid method

Manipulating the Document objects using getElementById() Method

HTML DOM is a programming interface enabling modification of web documents via functions. Focusing on HTML DOM, it empowers JavaScript to manipulate HTML tags, attributes, and elements. This guide elaborates on DOM properties, structure, methods, and benefits, fostering comprehensive understanding for web development.

Frequently Asked Questions on DOM

What do you mean by dom.

DOM stands for Document Object Model. It is a programming interface for web documents like HTML, XML and SVG documents. DOM represents elements of documents as tree of objects.

What is an example of a DOM?

DOM representation for a HTML code can be seen as: Document – HTML – head – title (text: “My Website”) – body – h1 (text: “Welcome!”) – p (text: “This is the main content.”)

What is DOM in JavaScript?

DOM in JavaScript refers to a programming interface. It provides a way to access, manipulate, and interact with the structure and content of an HTML document.

Why DOM is used in JavaScript?

DOM is used in JavaScript for many purposes like: Dynamically style and update content, performing client-side validation, event handling, etc.

Similar Reads

  • Web Technologies

Please Login to comment...

  • How to Underline in Discord
  • How to Block Someone on Discord
  • How to Report Someone on Discord
  • How to add Bots to Discord Servers
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

Attributes and properties

When the browser loads the page, it “reads” (another word: “parses”) the HTML and generates DOM objects from it. For element nodes, most standard HTML attributes automatically become properties of DOM objects.

For instance, if the tag is <body id="page"> , then the DOM object has body.id="page" .

But the attribute-property mapping is not one-to-one! In this chapter we’ll pay attention to separate these two notions, to see how to work with them, when they are the same, and when they are different.

DOM properties

We’ve already seen built-in DOM properties. There are a lot. But technically no one limits us, and if there aren’t enough, we can add our own.

DOM nodes are regular JavaScript objects. We can alter them.

For instance, let’s create a new property in document.body :

We can add a method as well:

We can also modify built-in prototypes like Element.prototype and add new methods to all elements:

So, DOM properties and methods behave just like those of regular JavaScript objects:

  • They can have any value.
  • They are case-sensitive (write elem.nodeType , not elem.NoDeTyPe ).

HTML attributes

In HTML, tags may have attributes. When the browser parses the HTML to create DOM objects for tags, it recognizes standard attributes and creates DOM properties from them.

So when an element has id or another standard attribute, the corresponding property gets created. But that doesn’t happen if the attribute is non-standard.

For instance:

Please note that a standard attribute for one element can be unknown for another one. For instance, "type" is standard for <input> ( HTMLInputElement ), but not for <body> ( HTMLBodyElement ). Standard attributes are described in the specification for the corresponding element class.

Here we can see it:

So, if an attribute is non-standard, there won’t be a DOM-property for it. Is there a way to access such attributes?

Sure. All attributes are accessible by using the following methods:

  • elem.hasAttribute(name) – checks for existence.
  • elem.getAttribute(name) – gets the value.
  • elem.setAttribute(name, value) – sets the value.
  • elem.removeAttribute(name) – removes the attribute.

These methods operate exactly with what’s written in HTML.

Also one can read all attributes using elem.attributes : a collection of objects that belong to a built-in Attr class, with name and value properties.

Here’s a demo of reading a non-standard property:

HTML attributes have the following features:

  • Their name is case-insensitive ( id is same as ID ).
  • Their values are always strings.

Here’s an extended demo of working with attributes:

Please note:

  • getAttribute('About') – the first letter is uppercase here, and in HTML it’s all lowercase. But that doesn’t matter: attribute names are case-insensitive.
  • We can assign anything to an attribute, but it becomes a string. So here we have "123" as the value.
  • All attributes including ones that we set are visible in outerHTML .
  • The attributes collection is iterable and has all the attributes of the element (standard and non-standard) as objects with name and value properties.

Property-attribute synchronization

When a standard attribute changes, the corresponding property is auto-updated, and (with some exceptions) vice versa.

In the example below id is modified as an attribute, and we can see the property changed too. And then the same backwards:

But there are exclusions, for instance input.value synchronizes only from attribute → property, but not back:

In the example above:

  • Changing the attribute value updates the property.
  • But the property change does not affect the attribute.

That “feature” may actually come in handy, because the user actions may lead to value changes, and then after them, if we want to recover the “original” value from HTML, it’s in the attribute.

DOM properties are typed

DOM properties are not always strings. For instance, the input.checked property (for checkboxes) is a boolean:

There are other examples. The style attribute is a string, but the style property is an object:

Most properties are strings though.

Quite rarely, even if a DOM property type is a string, it may differ from the attribute. For instance, the href DOM property is always a full URL, even if the attribute contains a relative URL or just a #hash .

Here’s an example:

If we need the value of href or any other attribute exactly as written in the HTML, we can use getAttribute .

Non-standard attributes, dataset

When writing HTML, we use a lot of standard attributes. But what about non-standard, custom ones? First, let’s see whether they are useful or not? What for?

Sometimes non-standard attributes are used to pass custom data from HTML to JavaScript, or to “mark” HTML-elements for JavaScript.

Also they can be used to style an element.

For instance, here for the order state the attribute order-state is used:

Why would using an attribute be preferable to having classes like .order-state-new , .order-state-pending , .order-state-canceled ?

Because an attribute is more convenient to manage. The state can be changed as easy as:

But there may be a possible problem with custom attributes. What if we use a non-standard attribute for our purposes and later the standard introduces it and makes it do something? The HTML language is alive, it grows, and more attributes appear to suit the needs of developers. There may be unexpected effects in such case.

To avoid conflicts, there exist data-* attributes.

All attributes starting with “data-” are reserved for programmers’ use. They are available in the dataset property.

For instance, if an elem has an attribute named "data-about" , it’s available as elem.dataset.about .

Multiword attributes like data-order-state become camel-cased: dataset.orderState .

Here’s a rewritten “order state” example:

Using data-* attributes is a valid, safe way to pass custom data.

Please note that we can not only read, but also modify data-attributes. Then CSS updates the view accordingly: in the example above the last line (*) changes the color to blue.

  • Attributes – is what’s written in HTML.
  • Properties – is what’s in DOM objects.

A small comparison:

Properties Attributes
Type Any value, standard properties have types described in the spec A string
Name Name is case-sensitive Name is not case-sensitive

Methods to work with attributes are:

  • elem.hasAttribute(name) – to check for existence.
  • elem.getAttribute(name) – to get the value.
  • elem.setAttribute(name, value) – to set the value.
  • elem.removeAttribute(name) – to remove the attribute.
  • elem.attributes is a collection of all attributes.

For most situations using DOM properties is preferable. We should refer to attributes only when DOM properties do not suit us, when we need exactly attributes, for instance:

  • We need a non-standard attribute. But if it starts with data- , then we should use dataset .
  • We want to read the value “as written” in HTML. The value of the DOM property may be different, for instance the href property is always a full URL, and we may want to get the “original” value.

Get the attribute

Write the code to select the element with data-widget-name attribute from the document and to read its value.

Make external links orange

Make all external links orange by altering their style property.

A link is external if:

  • Its href has :// in it
  • But doesn’t start with http://internal.com .

The result should be:

Open a sandbox for the task.

First, we need to find all external references.

There are two ways.

The first is to find all links using document.querySelectorAll('a') and then filter out what we need:

Please note: we use link.getAttribute('href') . Not link.href , because we need the value from HTML.

…Another, simpler way would be to add the checks to CSS selector:

Open the solution in a sandbox.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

TutorialsTonight Logo

JavaScript DOM Manipulation

In this tutorial, you are going to learn JavaScript DOM Manipulation . You will learn how to manipulate the DOM in javascript, why we need DOM manipulation, what can you do in DOM manipulation, etc.

Suppose you want to create an interactive web application that modifies content and elements on the application as as users interact with it.

You can achieve this by changing the webpage dynamically. These are the most common things that you will want to do.

Table Of Contents

  • What is DOM manipulation
  • Creating new element
  • Appending new element
  • Removing element
  • Replacing element
  • Changing style
  • Adding attribute
  • Removing attribute
  • Adding event listener
  • DOM manipulation cheat sheet
  • Practice DOM manipulation

javascript DOM manipulation

What is DOM Manipulation in javascript?

DOM Manipulation is the process of changing the content and structure of the DOM (document object model). The DOM can be modified by adding, removing, or modifying elements and their attributes.

JavaScript DOM manipulation includes any of the following:

  • Creating a new element
  • Attaching/appending a new element to the DOM
  • Removing an old element from the DOM
  • Replacing an element with another element
  • Changing the location of the element in the document
  • Making changes in existing elements by adding style or by adding content
  • Adding a new attribute to the element
  • Removing an attribute from the element
  • Changing the value of an attribute
  • Changing the events on the DOM

JavaScript DOM Manipulation Methods

To make some changes in DOM or to modify the DOM elements we need some methods given by JavaScript to do so.

Here is the list of the tasks that you can do using DOM manipulation methods:

1. Create Element In JavaScript

It is common for interactive websites to create new elements dynamically on user's actions and use them.

To create a new element in the DOM, we need to use the document.createElement() method and pass the name of the element as an argument.

Look at the example below:

The reference of the created element is returned by the document.createElement() method and stored in the variable.

The createElement() method converts the tag name of the element to lower case before creating the element. So you can pass element name both in lower case and upper case.

Note : The element created by the createElement() method does not automatically attach to the document, we have to explicitly append elements to the document.

2. Appending Element Using JavaScript

We have created the element and also has stored the reference of the element in a variable, but the created element is floating aimlessly because DOM does not know about the created element till now.

append element in javascript

To make the created element a part of the document we have to explicitly attach it to the document using some methods.

  • append() - It appends the Node objects or DOMString object to the parent element.
  • appendChild() - It can append only Node objects to the parent element.

Here is a working example:

Output: After button click

append element output

The reference of Node element which has to be appended is passed as an argument to the method. The method calling element is known as the parent while the element which is appended is called the child .

appending element to the parent element

3. Remove Element From DOM

In an interactive web application, you will not only want to create and append a new element to the document but also remove any desired element.

The removeChild() method is used to remove the child element from the parent element. The reference of the child element is passed as an argument to the method.

  • parentElement - The reference of the parent element.
  • childElement - The reference of the child element.

Here is an example that removes the child element from the parent element:

The method removeChild returns a reference to the child node which is deleted.

Note : You need to call the removeChild method from the parent of the child otherwise it will throw an error.

4. Replace Element with Other Element

The replaceChild() method is used to replace the child element with another element.

  • parentElement - Parent element whose child is to be replaced.
  • newChild - Element which will replace another one.
  • oldChild - Element which will be replaced.

The method returns the element which is replaced.

5. Changing Style of Element

You can also change the style of an element dynamically on an action. To change the style of an element you can use use the style property of the element.

With the style property, you can control any CSS property of the element like color, font, border, etc.

  • element - The element whose style is to be changed.
  • property - The property of the element whose value is to be changed.
  • value - The value of the property.

Here is an example that changes the color of the element:

6. Adding Attribute to Element

You can add an HTML attribute to an element using the setAttribute() method.

  • element - The element whose attribute is to be added.
  • attribute - The attribute of the element.
  • value - The value of the attribute.

Here is an example that adds the attribute title to the element:

7. Removing Attribute from Element

You can also remove attributes from an HTML element using the removeAttribute() method in JavaScript.

To remove an attribute call the method on the element and pass the attribute name as an argument.

8. Adding Event Listener to Element

The addEventListener() method is used to add an event listener to an element.

An event listener is a function that is called when an event occurs on an element.

  • element - The element on which the event is to be added.
  • event - The event which is to be added.
  • function - The function which is to be called when the event occurs.

Here is an example that adds mouseover event to the element:

Javascript DOM Manipulation Cheat Sheet

Javascript DOM Manipulation Cheat Sheet

Javascript DOM Manipulation Practice

Here are some practice problems to practice DOM manipulation.

  • Create a table element and add it to the body.
  • Create a table row element and add it to the table.
  • Remove 2nd row from the table.
  • Add a class attribute to the table row.
  • Replace 3rd row with a new row.
  • Add an event listener to the table.

JavaScript DOM manipulation is a powerful tool provided by the language using which we can do a lot of things with HTML. It is very useful when we want to add a lot of functionality to our website.

You can add, remove, change, add an event listener to an element using DOM manipulation.

With all this knowledge you can now create a lot of cool websites.

An introduction to the JavaScript DOM

An introduction to the JavaScript DOM

By Gabriel Tanner

The Javascript DOM (Document Object Model) is an interface that allows developers to manipulate the content, structure and style of a website. In this article, we will learn what the DOM is and how you can manipulate it using Javascript. This article can also be used as a reference for the basic DOM operations.

What is the DOM?

At the most basic level, a website consists of an HTML and CSS document. The browser creates a representation of the document known as Document Object Model (DOM). This document enables Javascript to access and manipulate the elements and styles of a website. The model is built in a tree structure of objects and defines:

  • HTML elements as objects
  • Properties and events of the HTML elements
  • Methods to access the HTML elements

Image

The places of the elements are referred to as nodes. Not only elements get nodes but also the attributes of elements and text get their own node (attribute-nodes and text-nodes).

DOM Document

The DOM Document is the owner of all other objects in your webpage. That means if you want to access any object on your webpage you always have to start with the document. It also contains many important properties and methods that enable us to access and modify our website.

Finding HTML Elements

Now that we understand what the DOM document is we can start getting our first HTML elements. There are many different ways to do so using the Javascript DOM here are the most common:

Get element by ID

The getElementById() method is used to get a single element by its id. Let’s look at an example:

Here we get the element with the id of header-title and save it into a variable.

Get elements by class name

We can also get more than one object using the getElementsByClassName() method which returns an array of elements.

Here we get all items with the class list-items and save them into a variable.

Get element by tag name

We can also get our elements by tag name using the getElementsByTagName() method.

Here we get all li elements of our HTML document and save them into a variable.

Queryselector

The querySelector() method returns the first element that matches a specified CSS selector. That means that you can get elements by id, class, tag and all other valid CSS selectors. Here I just list a few of the most popular options.

Get by class:

Get by tag:

Get more specific elements:

We can also get more specific elements using CSS Selectors .

In this example we search for a tag and a class at the same time and return the first element that passes the CSS Selector.

Queryselectorall

The querySelectorAll() method is completely the same as the querySelector() except that it returns all elements that fit the CSS Selector.

In this example, we get all h1 tags that have a class of heading and store them in an array.

Changing HTML Elements

The HTML DOM allows us to change the content and style of an HTML element by changing its properties.

Changing the HTML

The innerHTML property can be used to change the content of an HTML element.

In this example we get the element with an id of header and set the inner content to “Hello World!”.

InnerHTML can also be used to put tags in another tag.

Here we put a h1 tag into all already existing div.

Changing a value of an attribute

You can also change the value of an attribute using the DOM.

In this example we change the src of all _ t_ags to te_st.jpg.

Changing the style

To change the style of an HTML element we need to change the style property of our elements. Here is an example syntax for changing styles:

Now lets look at an example where we get an element and change the bottom border to a solid black line:

The CSS properties need to be written in camelcase instead of the normal css property name. In this example we used borderBottom instead of border-bottom.

Adding and deleting elements

Now we will take a look at how we can add new elements and delete existing ones.

Adding elements

Here we just create a div element using the createElement() method which takes a tagname as a parameter and saves it into a variable. After that we just need to give it some content and then insert it into our DOM document.

Here we create content using the createTextNode() method which takes a String as a parameter and then we insert our new div element before a div that already exists in our document.

Deleting elements

Here we get an element and delete it using the removeChild() method.

Replace elements

Now let’s take a look at how we can replace items.

Here we replace an element using the replaceChild() method. The first argument is the new element and the second argument is the element which we want to replace.

Writing directly into the HTML output stream

We can also write HTML expressions and JavaScript directly into the HTML output stream using the write() method.

We can also pass JavaScript expressions like a date object.

The write() method can also take multiple arguments that will be appended to the document in order of their occurrence.

Event Handlers

The HTML DOM also allows Javascript to react to HTML events. Here I’ve just listed some of the most important ones:

  • mouse click
  • input field change

Assign Events

You can define events directly in your HTML code using attributes on your tags. Here is an example of an onclick event:

In this example, the text of the

will change to “Hello!” when you click the button. You can also call functions when an event is triggered as you can see in the next example. <h1 onclick=”changeText( this )”>Click me!</h1> Here we call the changeText() method when the button is clicked and pass the element as an attribute. We can also assign the same events in our Javascript code. document .getElementById(“btn”).onclick = changeText();

Assign events listeners.

Now let’s look at how you can assign event listeners to your HTML elements.

Here we just assigned a clickevent that calls the runEvent method when our btn element is clicked.

You can also assign multiple events to a single element:

Node Relationships

The nodes in the DOM Document have a hierarchical relationship to each other. This means that the nodes are structured like a tree. We use the terms parent, sibling and child to describe the relationship between nodes.

The top node is called the root and is the only node that has no parent. The root in a normal HTML document is the tag because it has no parent and is the top tag of the document.

Navigating Between Nodes

We can navigate between nodes using these properties:

  • nextSibling

Here is an example how you can get the parent element of an h1.

You made it all the way until the end! Hope that this article helped you understand the Javascript DOM and how to use it to manipulate elements on your website.

If you want to read more articles just like this one you can visit my website or start following my newsletter .

If you have any questions or feedback, let me know in the comments down below.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Nullish coalescing assignment (??=)

The nullish coalescing assignment ( ??= ) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish ( null or undefined ).

Description

Nullish coalescing assignment short-circuits , meaning that x ??= y is equivalent to x ?? (x = y) , except that the expression x is only evaluated once.

No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

Neither would the following trigger the setter:

In fact, if x is not nullish, y is not evaluated at all.

Using nullish coalescing assignment

You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values , ??= also applies the default value if the property has value null .

Specifications

Specification

Browser compatibility

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

  • Nullish coalescing operator ( ?? )

JavaScript and the DOM

Print Cheatsheet

Nodes in DOM tree

A node in the DOM tree is the intersection of two branches containing data. Nodes can represent HTML elements, text, attributes, etc. The root node is the top-most node of the tree. The illustration shows a representation of a DOM containing different types of nodes.

DOM node

The DOM is an interface between scripting languages and a web page’s structure. The browser creates a Document Object Model or DOM for each webpage it renders. The DOM allows scripting languages to access and modify a web page. With the help of DOM, JavaScript has the ability to create dynamic HTML.

Accessing HTML attributes in DOM

The DOM nodes of type Element allow access to the same attributes available to HTML elements. For instance, for the given HTML element, the id attribute will be accessible through the DOM.

The Document Object Model

The Document Object Model , or DOM is a representation of a document (like an HTML page) as a group of objects. While it is often used to represent HTML documents, and most web browsers use JavaScript interfaces to the DOM, it is language agnostic as a model.

The DOM is tree-like and heirarchical, meaning that there is a single top-level object, and other objects descend from it in a branching structure.

The removeChild() Method

The .removeChild() method removes a specified child from a parent element. We can use this method by calling .removeChild() on the parent node whose child we want to remove, and passing in the child node as the argument.

In the example code block, we are removing iceCream from our groceryList element.

The element.parentNode Property

The .parentNode property of an element can be used to return a reference to its direct parent node. .parentNode can be used on any node.

In the code block above, we are calling on the parentNode of the #first-child element to get a reference to the #parent div element.

The document.createElement() Method

The document.createElement() method creates and returns a reference to a new Element Node with the specified tag name.

document.createElement() does not actually add the new element to the DOM, it must be attached with a method such as element.appendChild() .

The element.InnerHTML Property

The element.innerHTML property can be used to access the HTML markup that makes up an element’s contents.

element.innerHTML can be used to access the current value of an element’s contents or to reassign it.

In the code block above, we are reassigning the box element’s inner HTML to a paragraph element with the text “Goodbye”.

The document Object

The document object provides a Javascript interface to access the DOM. It can be used for a variety of purposes including referencing the <body> element, referencing a specific element with ID, creating new HTML elements, etc.

The given code block can be used to obtain the reference to the <body> element using the document object.

The document.getElementById() Method

The document.getElementById() method returns the element that has the id attribute with the specified value.

document.getElementById() returns null if no elements with the specified ID exists.

An ID should be unique within a page. However, if more than one element with the specified ID exists, the .getElementById() method returns the first element in the source code.

The .querySelector() Method

The .querySelector() method selects the first child/descendant element that matches its selector argument.

It can be invoked on the document object to search the entire document or on a single element instance to search that element’s descendants.

In the above code block, we are using .querySelector() to select the first div element on the page, and to select the first element with a class of button , inside the .main-navigation element.

The document.body Object

document.body returns a reference to the contents of the <body> HTML element of a document/HTML page. The <body> element contains all the visible contents of the page.

The element.onclick Property

The element.onclick property can be used to set a function to run when an element is clicked. For instance, the given code block will add an <li> element each time the element with ID addItem is clicked by the user.

The element.appendChild() Method

The element.appendChild() method appends an element as the last child of the parent.

In the given code block, a newly created <li> element will be appended as the last child of the HTML element with the ID list .

The element.style Property

The element.style property can be used to access or set the CSS style rules of an element. To do so, values are assigned to the attributes of element.style .

In the example code, blueElement contains the HTML element with the ID colorful-element . By setting the backgroundColor attribute of the style property to blue, the CSS property background-color becomes blue.

Also note that, if the CSS property contains a hyphen, such as font-family or background-color , Camel Case notation is used in Javascript for the attribute name, so background-color becomes backgroundColor .

The DOM Parent-Child Relationship

The parent-child relationship observed in the DOM is reflected in the HTML nesting syntax.

Elements that are nested inside the opening and closing tag of another element are the children of that element in the DOM.

In the code block, the two <p> tags are children of the <body> , and the <body> is the parent of both <p> tags.

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 events.

HTML DOM allows JavaScript to react to HTML events:

Reacting to Events

A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.

To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:

Examples of HTML events:

  • When a user clicks the mouse
  • When a web page has loaded
  • When an image has been loaded
  • When the mouse moves over an element
  • When an input field is changed
  • When an HTML form is submitted
  • When a user strokes a key

In this example, the content of the <h1> element is changed when a user clicks on it:

In this example, a function is called from the event handler:

Advertisement

HTML Event Attributes

To assign events to HTML elements you can use event attributes.

Assign an onclick event to a button element:

In the example above, a function named displayDate will be executed when the button is clicked.

Assign Events Using the HTML DOM

The HTML DOM allows you to assign events to HTML elements using JavaScript:

In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn" .

The function will be executed when the button is clicked.

The onload and onunload Events

The onload and onunload events are triggered when the user enters or leaves the page.

The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

The onload and onunload events can be used to deal with cookies.

The oninput Event

The oninput event is often to some action while the user input data.

Below is an example of how to use the oninput to change the content of an input field.

The onchange Event

The onchange event is often used in combination with validation of input fields.

Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an input field.

The onmouseover and onmouseout Events

The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element:

Try it Yourself »

The onmousedown, onmouseup and onclick Events

The onmousedown , onmouseup , and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.

More Examples

onmousedown and onmouseup Change an image when a user holds down the mouse button.

onload Display an alert box when the page has finished loading.

onfocus Change the background-color of an input field when it gets focus.

Mouse Events Change the color of an element when the cursor moves over it.

HTML DOM Event Object Reference

For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference .

Test Yourself with Exercises!

Exercise 1 »    Exercise 2 »    Exercise 3 »

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

COMMENTS

  1. JavaScript DOM

    JavaScript DOM - Exercises, Practice, Solution Last update on May 18 2023 13:10:54 (UTC/GMT +8 hours) JavaScript DOM [13 exercises with solution] [An editor is available at the bottom of the page to write and execute the scripts. Go to the editor] 1. Here is a sample html file with a submit button. Now modify the style of the paragraph text ...

  2. JavaScript HTML DOM

    The HTML DOM is a standard object model and programming interface for HTML. It defines: The HTML elements as objects. The properties of all HTML elements. The methods to access all HTML elements. The events for all HTML elements. In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

  3. JavaScript DOM Practice Exercises For Beginners

    Video 3: Exercise 2. See the code and full exercise on Codepen. To make the ordering of the plans more logical, using JavaScript, move the basic plan to be before (to the left) of the pro plan. In Video 3 we had a simple pricing table with two products, a basic and pro plan and this was an exercise in moving elements around in the DOM.

  4. The JavaScript DOM Manipulation Handbook

    The JavaScript DOM Manipulation Handbook. By Benjamin Semah. DOM Manipulation is one of the most exciting topics to learn about in JavaScript. This is because one of JavaScript's main uses is to make web pages interactive - and the Document Object Model (DOM) plays a major role in this. The DOM is a powerful tool that allows you to interact ...

  5. JavaScript in the Browser

    There are different ways to assign event handlers in JavaScript: HTML Attribute: You can set an event handler directly in the HTML code using an attribute like onclick, onmouseover, etc. < button onclick = "alert('Button clicked!')" > Click me </ button > DOM Property: You can assign a handler using a DOM property like onclick, onmouseover, and ...

  6. Manipulating documents

    Manipulating documents. When writing web pages and apps, one of the most common things you'll want to do is manipulate the document structure in some way. This is usually done by using the Document Object Model (DOM), a set of APIs for controlling HTML and styling information that makes heavy use of the Document object.

  7. How the JavaScript DOM Works

    The DOM is a Web API that allows developers to use programming logic to make changes to their HTML code. It's a reliable way to make changes that turn static websites into dynamic ones. It's an important topic in web development because the DOM serves as the initial use of JavaScript in the browser. HTML code isn't considered part of the DOM ...

  8. The Modern JavaScript DOM Cheat Sheet

    This article provides a comprehensive cheat sheet for modern JavaScript DOM, covering a wide range of methods and properties that you can use to interact with the Document Object Model in your web applications. Table Of Contents. 1 Selecting Elements. 2 Creating and Modifying Elements.

  9. DOM Manipulation and Events

    Document Object Model. The DOM (or Document Object Model) is a tree-like representation of the contents of a webpage - a tree of "nodes" with different relationships depending on how they're arranged in the HTML document. There are many types of nodes, most of which are not commonly used.

  10. Document Object Model (DOM)

    Document Object Model (DOM) The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document—such as the HTML representing a web page—in memory. Usually it refers to JavaScript, even though modeling HTML, SVG, or XML documents as objects are not part of the core JavaScript ...

  11. JavaScript HTML DOM Examples

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  12. Introduction to the DOM

    The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page. A web page is a document that can be either displayed in ...

  13. How can I add a class to a DOM element in JavaScript?

    The className way. This is the simple way, storing all classes in a string. The string can easily be changed or appended. // Create a div and add a class. var new_row = document.createElement("div"); new_row.className = "aClassName"; // Add another class. A space ' ' separates class names.

  14. The Modern JavaScript Tutorial

    Modern JavaScript Tutorial: simple, but detailed explanations with examples and tasks, including: closures, document and events, object oriented programming and more. ... Destructuring assignment. Date and time. JSON methods, toJSON ... Shadow DOM slots, composition. Shadow DOM styling. Shadow DOM and events. Regular expressions. Patterns and ...

  15. DOM Manipulation in JavaScript

    The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text. JavaScript can manipulate this tree structure, allowing developers to dynamically alter the content and ...

  16. HTML DOM (Document Object Model)

    The Document Object Model (DOM) is essential in web development for several reasons: Dynamic Web Pages: It allows you to create dynamic web pages. It enables the JavaScript to access and manipulate page content, structure, and style dynamically which gives interactive and responsive web experiences, such as updating content without reloading the entire page or responding to user actions instantly.

  17. Attributes and properties

    All attributes are accessible by using the following methods: elem.hasAttribute(name) - checks for existence. elem.getAttribute(name) - gets the value. elem.setAttribute(name, value) - sets the value. elem.removeAttribute(name) - removes the attribute. These methods operate exactly with what's written in HTML.

  18. JavaScript DOM Manipulation (8 Methods)

    JavaScript DOM manipulation includes any of the following: Creating a new element. Attaching/appending a new element to the DOM. Removing an old element from the DOM. Replacing an element with another element. Changing the location of the element in the document. Making changes in existing elements by adding style or by adding content.

  19. Learn DOM Manipulation In 18 Minutes

    🚨 IMPORTANT:JavaScript Simplified Course: https://javascriptsimplified.comDOM manipulation is tough. There are lots of methods and techniques you need to ma...

  20. An introduction to the JavaScript DOM

    The browser creates a representation of the document known as Document Object Model (DOM). This document enables Javascript to access and manipulate the elements and styles of a website. The model is built in a tree structure of objects and defines: HTML DOM model. The places of the elements are referred to as nodes.

  21. Nullish coalescing assignment (??=)

    No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

  22. JavaScript and the DOM

    The Document Object Model, or DOM is a representation of a document (like an HTML page) as a group of objects. While it is often used to represent HTML documents, and most web browsers use JavaScript interfaces to the DOM, it is language agnostic as a model. The DOM is tree-like and heirarchical, meaning that there is a single top-level object ...

  23. JavaScript

    The HTML DOM can be accessed with JavaScript (and with other programming languages). In the DOM, all HTML elements are defined as objects. The programming interface is the properties and methods of each object. A property is a value that you can get or set (like changing the content of an HTML element). A method is an action you can do (like ...

  24. JavaScript HTML DOM Document

    3. document.lastModified. Returns the date and time the document was updated. 3. document.links. Returns all <area> and <a> elements that have a href attribute. 1. document.readyState. Returns the (loading) status of the document.

  25. JavaScript HTML DOM Events

    Reacting to Events. A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element. To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute: onclick= JavaScript. Examples of HTML events: When a user clicks the mouse. When a web page has loaded. When an image has been loaded.

  26. DOM Manipulation in JavaScript || Class 38.

    🎯 Welcome to the ultimate JavaScript DOM tutorial! In this video, you will learn how to link HTML, CSS, and JavaScript files seamlessly and dive deep into D...