×
Community Blog Accessing DOM Elements

Accessing DOM Elements

This tutorial outlines how you can access DOM elements through ID, class, tag, and query selectors.

By Alex Muchiri.

Previously, we looked at how the DOM is structured into trees and nodes, discussed some of the basics of getting elements in the DOM, and learned about three types of nodes, specifically text, comment, and element nodes. DOM content can be accessed through the element node.

Now, in this tutorial, we will be exploring the methods of accessing DOM elements through ID, class, tag, and query selectors. To follow this tutorial, you'll need to have working understanding of the HTML elements, CSS selectors, and the related syntax.

Methods

There are five methods for accessing elements in a document.

- document.getElementById(id) 
- document.getElementsByClassName(className)
- document.getElementsByTagName(tagName)
- document.querySelector(cssSelector)
- document.querySelectorAll(cssSelector)

Of these methods, the getElementById and querySelector methods return a single object element when employed. Consider the JavaScript example below:

var myText = document.getElementById("1");
myText.innerHTML = "Some text here";

On the other hand, the getElementsByClassName and getElementsByTagName methods return an array-like HTMLCollection object. The array-like collection includes all elements as they are added under the tag name or class name.

var examples = document.getElementsByClassName("examples ");
for (var i = 0; i < examples.length; i++) {
   console.log(examples[i].innerHTML);
}

Finally, the querySelectorAll() method returns an array-like NodeList, which is different from the HTMLCollection object above in that it does not automatically update if new elements are added to the page.

var examples = document.querySelectorAll(".examples ");
for (var i = 0; i < examples.length; i++) {
   console.log(examples[i].innerHTML);
}

Now, let's look at these methods in detail in the sections below.

Method One: getElementById()

In this section, we will be closely examining the getElementById() method. This method returns and element with the specified ID property, usually just one object since IDs are unique. It enables quick access to any element in the search field. However, if you want to access an element that does not have an ID, use querySelector(). Note that an ID is case-sensitive and represents only one element in a document. The returned value is either an Element object or a null value. Below is an HTML document example that you can work with:

<html>
<head>
  <title>getElementById method</title>
</head>
<body>
  <p id="1">Some text here</p>
  <button onclick="changeColor('green');">green</button>
  <button onclick="changeColor('blue');">blue</button>
</body>
</html>

If you want to use the method in JavaScript, below is the syntax to follow:

var element = document.getElementById(id);

Let's now create some JavaScript code to explore this method:

function someStyle(newStyle) {
  var element = document.getElementById('1');
  element.style.style = newStyle;
}

Since we have an element with an ID 1, the returned 'element' will contain an object 'Some text here' that will be manipulated with the JavaScript function.

Method Two: getElementByClassName()

This method, when called, returns an array-like object that includes all elements with the class name. It allows calling an entire document or a single element. When a document is called, all elements in the class name in the entire document are returned. On the contrary, when only one element is called, only those elements in the root element and in the specified class name are returned. Below is an example of how to implement this syntax:

var searchResult = document.getElementsByClassName(class); 
var searchResult = rootElement.getElementsByClassName(class);

The involved parameters are as described:

  • searchResult: returned search objects
  • class: the name of class to match in the search

Consider the HTML example below:

<html>
<body>
    <div id="id-1">
        <p>some text</p>
        <p class="some">some text 2</p>
        <p class="some">some text 3</p>
        <p class="other">some text 4</p>
    </div>
</body>
</html>

In the above case, we could simply search the entire document for all objects in a specified class, or we could couple several methods to refine the returned result even further.

    var myData = document.getElementById("id-1");
    var info = myData.getElementsByClassName("some");
        console.log(info); 

Once we obtain the HTMLCollection, it can be used in any way we wish. We began by searching for all elements with id-1, then searched returned value by the class name "some".

Method Three: getElementsByTagName

The getElementsByTagName is another method that returns a HTMLCollection, for all objects with the specified tag name. Since the HTMLCollection is live, you do not need to call the document again for updates. Below is the syntax for this method:

var myList = document.getElementsByTagName(myTag);

The required parameters are as follows:

  • a placeholder for the HTMLCollection returned myList
  • a name for the tag myTag

Let us explore this method in an example using the HTML example below:

<!DOCTYPE html>
<html>
<head>
<style>
div {
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>

<div id="text">
  <p> This is some element in div (index 0).</p>
  <p> This is some other element in div (index 1).</p>
  <p> This is yet another element in div(index 2).</p>
</div>

<p> Some text here: click button to change some color on some paragraph in some element. </p>

<button onclick="changeColor()">Try it</button>

</body>
</html>

The JavaScript to execute a color change can be implemented like so:

<script>
function changeColor() {
  var something = document.getElementById("text");
  something.getElementsByTagName("P")[1].style.backgroundColor = "green";
}
</script>

To explain, the function will look through the document for an element with an id text, then search within the returned object for elements identified by the specified tag and index 1 to apply a color change.

We have in effect executed two functions. The first was to search through the entire document for an element, then starting at the element, we search for an object or objects identified by the specified tag.

Method Four: querySelector()

The querySelector() method looks through a document and only returns the first element matching the search criteria. The method returns a null value is there are no matches to return. Usually, the search starts with the first element in the document, iterating through subsequent nodes based on the children associated with each node. Below is the general syntax:

myVariable = document.querySelector(selectors);

The only necessary parameter is some selector string, which must match some CSS selector string. Since the method returns only one element, you may consider using querySelectorAll() to get more than one value returned in the HTMLElement. If the parameter can be matched by more than one element, the first value will be returned and the others ignored.

Consider HTML example below.

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
  border: 1px solid black;
}
</style>
</head>
<body>

<div id="text">
  <h2 class="classes">This is a header section with some text="example" in div</h2>
  <p class="classes">This is a paragraph section with some text="example" in div.</p> 
</div>

<p>some text here: this button when clicked will change the text in some element identified by some class in the div.</p>

<button onclick="helloFunction()">Try it</button>

</body>
</html>

Now consider the JavaScript function:

<script>
function helloFunction() {
  var a = document.getElementById("text");
  a.querySelector(".example").innerHTML = "Howdy my friend!";
}
</script>

Query selectors must follow CSS syntax standards or an error will be thrown. However, you may escape this problem by using colon or space whenever an ID or selector does not observer these standards. For instance, use the backlash twice for literal strings representations to escape the JavaScript and querySelector() errors.

Method Five: querySelectorAll()

The querySelectorAll() method when called, returns a collection of child elements for a matching parent element specified in the selector criteria. The returned collection is in the form of a NodeList, and therefore, it is not live and must be run again if any changes are made. The list is indexed, meaning we can iterate through it using node indices starting from 0. The iteration through indices enables CSS property changes to be effected through all returned nodes or particular nodes. Below is the syntax for this method:

element.querySelectorAll(selectors)

If implemented based on the ParentNode method, we get the syntax below:

elementList = parentNode.querySelectorAll(selectors);

If the search entails multiple selectors, they should be separated with commas. The only parameter for this method is the selectors, which should be a DOMString, which in turn must satisfy CSS selector requirements to avoid throwing errors. See HTML example in the below:

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>

<div id="text">
  <p>This is some text in the element p div.</p>
  <p> This is some other text in the element p div.</p>
</div>

<p> Add some green color flavour to the second element in div by clicking on this button.</p>

<button onclick="JSqueries()">Try it</button>

<p><strong>Note:</strong> Some other text down here, howdy!!.</p>
</body>
</html>

Consider the JavaScript script below to learn how to code the selector:

<script>
function JSqueries() {
  var s = document.getElementById("text").querySelectorAll("p");
  s[1].style.backgroundColor = "green";
}
</script>

To explain, the function searched the entire document for an element with the id text, and then in that element, searched using the selector p and returned an indexed NodeList, which we then applied the green color on it.

Conclusion

In this tutorial, we have covered five different ways of accessing HTML elements in the DOM. The choice of a method depends on the elements being manipulated. All the five (ID, class, HTML tag name, and selector) have their merits and drawbacks. On the whole, you should now find accessing HTML elements using JavaScript through the DOM much easier.

Don’t have an Alibaba Cloud account? Sign up for an account and try over 40 products for free. This deal is worth up to $1300. Get Started with Alibaba Cloud to learn more.

The views expressed herein are for reference only and don't necessarily represent the official views of Alibaba Cloud.

0 0 0
Share on

Alibaba Clouder

2,599 posts | 762 followers

You may also like

Comments