What is the HTML DOM?
It’s a data structure which represents every HTML tag present on the page – everything from the root <html> element that wraps your page to every <div>, <p>, <input>, and <em> – everything on the page is represented in the DOM, both content and structure.
The style of each element is part of the DOM – so any CSS property can be changed, including the color, background, position and orientation of elements.
Updating DOM Elements Attributes with setAttribute()
Attributes are values within HTML elements that configure how the element behaves, assign it a value, or otherwise dictate what it does on the page.
A full list of standard HTML attributes is available here.
Custom attributes can also be set, which you can set and read for your own purposes.
setAttribute() Method Syntax
- NAME is the name of the HTML Attribute which you wish to set or update
- VALUE is the value that the attribute will be set to
- All values for VALUE will be converted to string
- If using boolean, the presence of a value, no matter what it is, will be considered TRUE, and an empty string will be considered FALSE
setAttribute() Method Example
<input id="my-input"> <script> var myInput = document.getElementById("my-input"); myInput.setAttribute("disabled", ""); myInput.setAttribute("value", "This input has been disabled"); </script>
First, an input with id my-input is defined.
The input element is then modified using its setAttribute method – first it is disabled, then its value is updated to let the user know that it is disabled.
There are many reasons you may want to modify the HTML attributes of on-page elements:
- Showing and hiding menus
- Changing the color of a read notification
- Hiding text that doesn’t fit on-screen
- Resizing images
- Moving on-screen objects for animation
- Adding HTML events to objects to enable or disable buttons or change their behavior
- … And what ever other reasons you can think of – get creative!