Javascript Get Element by Class: Searching for Elements

javascript get element by classJavaScript first appeared on the scene in 1995 as part of the Netscape Navigator 2 beta browser. It allowed web pages to interact with users to a greater degree than before. JavaScript code cannot exist by itself- it must be embedded inside regular HTML code (or even CSS code). JavaScript can be said to be an extension of regular HTML code. As such, JavaScript is not like the Java language, though the two languages are compatible to a large degree.

Java and JavaScript

You will find it easy to learn JavaScript if you’re familiar with Java. JavaScript is an object oriented scripting language, while Java is an object oriented programming language. There are major differences between the two (JavaScript can only be run inside browsers, for example), but they are both languages that revolve around the concept of manipulating objects to perform programming tasks.

Today, JavaScript is used by almost all webpages and by major websites like Facebook and Twitter. JavaScript is also compatible with all major browsers like Chrome, Firefox and Internet Explorer. If you’re looking to become a website designer or even a computer programmer, it’s almost essential that you have a basic understanding of JavaScript to be good at what you do.

Classes in JavaScript

There are no classes as such in JavaScript, like there are in Java. Functions can be used to simulate classes to a large degree, but they can’t replace classes entirely. Objects in JavaScript, however, can implement the concept of inheritance that is found in other class oriented languages like Java.

JavaScript objects operate under the Document Object Model convention that is common to HTML, XML and XHTML.

However, because JavaScript does not exist on its own, it may be used in languages that do support classes – like CSS.

JavaScript getElementsByClassName

What is this element that we keep referring to (in the case of HTML)? An element in HTML (and, by extension, JavaScript) is everything that is enclosed between the start tag and the end tag that encloses a line of code. An example of an element is as follows:

<p> The Start and End tags are the Element </p>

In this case, the element is <p> and </p> and everything in between is the content of the element. There can be empty elements, and there can be elements that are nested inside other elements in HTML. Sound confusing? Think of a HTML program as a collection of elements that have relationships with each other and work together to build a single working program.

<body>
<p> The Start and End tags are the Element </p>
</body>

In this example, there are two elements: <body> and <p>. The element <p> is nested inside the element <body>. They will, in turn, be nested inside another element called <html>.

Because objects can be the parent “class” of other objects in JavaScript, we can query the parent “class” to find out the elements of that “class”. The elements of that class will, of course, have names of their own. You can do this with the use of the getElementsByClassName. Does it confuse you? Simply put, what this command does is search through classes that match our query and return elements of these classes.

Let’s see how the getElementsByClassName command works. If you wanted to search through the entire document to get certain elements, you would use the following line of code:

elements = document.getElementsByClassName (namesofclassestobesearched)

If you wanted to search through a particular element for its child elements (for child classes of a parent class), you use the following line of code:

elements = startingElement.getElementsByClassName (namesclassestobesearched)

For example, if your parent class was named Animals and you wanted to search through it for dogs, then Animals would be the startingElement in your code.

You can search for multiple classes at one time through this command. This command employs string variables.

We can take a few examples to help you understand it better. For example, if you had a class called “movies”, you can get all elements that have this class with the following command:

document.getElementsByClassName (‘movies’);

If you wanted to get elements that have two classes called “movies” and “games”, use the following line of code:

document getElementsByClassName (‘movies games’)

Here, the two classes have to be separated by a whitespace ( ).

What if some elements we wanted to find were located in another element in our document? You can search through an element that has an id of “entertainment” to search for elements belonging to class “movies” with the following line of code:

document.getElementsById(‘entertainment’).getElementsByClassName(‘movies’);

Using getElementsByClassName as a Function

The getElementsByClassName can also be used as a function in CSS (it will still return an array). We’ve written a program to demonstrate its use. You will also need to have an understanding of the getElementsByTagName command that is used in CSS (and of functions, arrays and loops in general):

function getElementsByClassName(_className, startElem, filterTag)
{
  if (typeof className === 'string')
     { _className = new RegExp('(^| )' + _className + '( |$)'); }

  startElem = startElem || document;

  filterTag = filterTag || '*';
  var arr = [];  
  var tags;      

  if (typeof startElem.all != 'undefined' && filterTag == '*')
  {
     tags = startElem.all;
  }
  else
  {

     tags = startElem.getElementsByTagName(filterTag);
  }
  var i, len = tags.length;
  for (i = 0; i < len; i++)
  {
     var elem = tags[i];
     if (_className.test(elem.className))

        { arr.push(elem); }
  }
  return arr;
}

Explanation: In the above code, we’ve instructed JavaScript to search through the entire document all elements by taking the values of the two parameters (which are optional) startElem and filterTag as default. The first parameter (className) is always required. The result of the query will be returned to you in an array format (var arr= []). We use a loop to search through the tags array we defined earlier to search for elements with names matching our query.

The .getElementsByClassName command is very useful when we want to search for an element without knowing its ID (as long as you have a class name to search through). This command is not very useful if you have a single page – but if your website has dozens of pages that you need to search through, it can be a lifesaver.

We hope this gave you a good idea of how to search for elements by their class name. If you need a refresher, feel free to go back to this beginners Javascript course. Once you’re comfortable with the basics, try your hand at creating your own interactive website.