JavaScript HTML DOM Elements
The HTML DOM (Document Object Model) is a programming interface that represents the structure of an HTML document as a tree of nodes and objects.
Each node in the tree corresponds to an HTML element, attribute, or text node.
Some of the most common HTML DOM elements include:
<html>
- The root element of an HTML document.<head>
- The container for metadata such as title, scripts, and stylesheets.<body>
- The container for the main content of an HTML document.<div>
- A container element that groups other HTML elements together.<p>
- The paragraph element, used to denote a paragraph of text.<a>
- The anchor element, used to create hyperlinks.<img>
- The image element, used to display images.<ul>
and<ol>
- The unordered and ordered list elements, respectively.<li>
- The list item element, used within<ul>
or<ol>
to denote individual list items.<table>
- The table element, used to create tables of data.<tr>
- The table row element, used to denote a row within a table.<td>
- The table cell element, used to denote a cell within a table.<form>
- The form element, used to create user input forms.<input>
- The input element, used to create various types of form inputs such as text fields, checkboxes, and radio buttons.<button>
- The button element, used to create clickable buttons.
Finding HTML Element by Id
To find an HTML element by its ID using JavaScript, you can use the document.getElementById()
method.
As an example:
Editor
In this example:
- The
document.getElementById()
method is used to get the HTML element with the ID"myHeading"
. - This element is then assigned to the
heading
variable. - The
console.log()
method is used to output the inner HTML of the heading element.
The getElementById()
method returns null
if no element with the specified ID exists
Finding HTML Elements by Tag Name
To find HTML elements by their tag name using JavaScript, you can use the document.getElementsByTagName()
method. This method returns a live HTMLCollection object of all the elements with the specified tag name.
As an example:
Editor
In this example:
- The
document.getElementsByTagName()
method is used to get all the<p>
elements in the HTML document. - The returned HTMLCollection object is assigned to the
paragraphs
variable. - A
for
loop is then used to iterate over theparagraphs
HTMLCollection object, and theinnerHTML
property is used to output the contents of each<p>
element to the console.
The getElementsByTagName()
method is case-insensitive. This means that getElementsByTagName("p")
and getElementsByTagName("P")
will both return the different result.