Methods

Accessing Methods

In JavaScript, there are different methods which are used in order to access the elements of a document object.

 

There are certain methods are as follows:

 

Method

Description

document.getElementById(id)

Find an element by using id.

document.getElementsByClassName(name)

Find the elements by using class name.

document.getElementsByTagName(name)

Find the elements by using tag name.

 

 

The getElementById() method

This method is used in order to find the element of an HTML document with the help of a specific id.

It is an effective method to access an element by using the specific ID. But, it can’t be quite useful in accessing the multiple elements.

 

Code:

<html>
<head>
<title></title>
</head>
<body>
<h2>JavaScript DOM </h2>
<h3>Welcome</h3>
<h4 id ="text">TutorialsLink!</h4>
<script>
document.getElementById("text").innerHTML;
</script>
</body>
</html>

 

Output:

 

 

 

 

The getElementsByClassName() method

This method helps in finding all the elements of a document object by using the same class name and return them as an array output.

 

Code:

<html>
<head>
<title></title>
</head>
<body>
<h2>JavaScript DOM </h2>
<h3 class = "text">Welcome</h3>
<h4 class ="text">TutorialsLink!</h4>
<script>
var arr = document.getElementsByClassName("text");
document.write(arr[1].innerHTML);
</script>
</body>
</html>

 

Output:

 

 

 

The getElementsByTagName() method

This method is used to access the all elements and attributes of a document object by using tag name. It also returns an array of all the values which have the same tag name.

 

Code:

<html>
<head>
<title></title>
</head>
<body>
<h2>JavaScript DOM </h2>
<p>Welcome</p>
<p>TutorialsLink!</p>
<script>
var arr = document.getElementsByTagName("p");
document.write(arr[1].innerHTML);
</script>
</body>
</html>

 

Output: