Working with the Element Node

Targeting by ID - getElementById()

As per HTML standards, an element's ID value must be unique to the document. In other words, there can be only one ID per page.

<div id="header">
    <h1><a href="/" id="homelink">Title of your site</a></h1>

In the above HTML snippet consisting of two ID values, we can access each element(node) by getElementById(). There are other ways to access these elements, but performance-wise, this is the fastest. We have to access the document object before you can get to the node you want.

document.getElementById ("header");

document.getElementById ("homelink");

Because IDs are unique to each document, getElementById() can return only a single element.

Using IDs throughout your HTML is not only great for JavaScript performance but also CSS performance and specificity when applying styles. IDs can also be used for accessibly enhancements when creating jump or “skip to content” links for screen readers or visually impaired users.
Targeting by Tag Name - getElementsByTagname()

Sometimes we need more than one, or even a group of elements. In this case, we use getElementsByTagName(). We can both target a group of elements and a single element inside of a group.

<!doctype html>

    <meta charset="utf-8">
    <title>getElementsByTagname Example</title>

    <h1>Using getElementsByTagname</h1>
    <p>Content paragraph</p>
    <p>Content paragraph</p>
    <p>Content paragraph</p>

Related Tutorial
Follow Us #
Contents +