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>
</div>

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.

Note
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>
<html>

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

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

</html&
gt;
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +