Wednesday, June 14, 2017

Referencing Elements in JavaScript

Hi all, In here we are going to discuss about how to reference elements in JavaScript. That means how to find and access HTML elements in a HTML page. There are several ways to do it. They are,

  1. Find HTML elements by id
  2. Find HTML elements by tag name
  3. Find HTML elements by class name
  4. Find HTML elements by CSS selectors
Let's try to understand each of these by using examples.

Find HTML elements by id

Example 1
Figure 1

In here, document.getElementById(‘paragraph’) is a method belongs to document object. It search through entire document and look for the element with id called 'paragraph'. Then it can be found and changed them. In here, we put an event, onclick, inside the paragraph. So, when we click the paragraph, 'click here', it calls function 'change'. Inside the paragraph, document.getElementById(‘paragraph’) method is used. So, then element with id named 'paragraph' is searched through the document and found. Then, by using 'par.innerHTML' , paragraph is replaced.

Result is shown in Figure 2.

Figure 2

When paragraph is clicked, it changed as Figure 3.
Figure 3

Find HTML elements by tag name

This is similar as the above one. Only difference is, tag name is used instead id in here.

Example 2


Figure 4

In here, there are several paragraphs. By using document.getElementByTagName("p"), all the paragraphs are searched. Then paragraph with id 'paragraph' is replaced by the first paragraph in here.
So result is as follows.


Figure 5

Find HTML elements by class name

In here, class name is used to find the HTML element. 

Example 3
Figure 6

In here, paragraph is searched using the class name. There are several classes with same class name. So, para[0] is used to select the first paragraph. 
Result is as follows.

Figure 7

Find HTML elements by CSS selectors

In here "querySelectorAll" method is used to find HTML elements.

Example 4

Figure 8
Result is shown in Figure 9.
Figure 9

Please go through the examples and try on your own. It will help you to understand about referencing elements. Thank you.