To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

Selecting elements in the DOM

One of JavaScript's purposes is to manipulate the DOM. To do this, JavaScript provides a few selection functions.

IDs, classes and tags

There are three ways of defining an element. The first is giving it a unique ID:

HTML
<div id="myid"></div>
    

IDs are unique and only one element can have an ID.

The alternative to IDs is classes, which specify what class(es) an element belongs to:

HTML
<div class="class1"></div>
<div class="class2"></div>
<div class="class2"></div>
<div class="class1 class2"></div>
    

Classes can be used over and over and can be combined.

The final type of element is one with neither of these.

HTML
<div></div>
    

Selecting elements

The first of these is selecting by ID. This will return precisely one element:

HTML
<div id="myid"></div>
<script>
  var e = document.getElementById('myid');
  console.log(e);
</script>
    

The next method will return an array of all elements with a class.

HTML
<div class="class1"></div>
<div class="class2"></div>
<div class="class2"></div>
<div class="class1 class2"></div>
<script>
  var e = document.getElementByClassName('class1');
  console.log(e);
</script>
    

As mentioned before, an array has a set of different items that can be accessed by their index.

Finally, it is possible to select all elements of a certain type. For instance, it is possible to select all img tags or all div on the document.

HTML
<div></div>
<div></div>
<div></div>
<div class="class2"></div>
<div class="class1 class2"></div>
<script>
  var e = document.getElementByTagName('div');
  console.log(e);
</script>
    

Once again, a set of elements will be returned.

Query selection

Query selecion is a more powerful method of finding elements. It is more similar to the CSS manner of selecting elements to affect.

There are two main rules for selection with CSS that are used with this:

  • . represents a class
  • # represents an ID

CSS however, is not limited to simple class and ID selection. In fact there are many other ways that CSS can select. This also translates to JavaScript being able to select the same way:

  • input[type=text] selects all input elements which have the type 'text'.
  • div:first-child selects the first child

There are plenty more of these, but they are not for the JavaScript tutorial.

To utilise the query selector in JavaScript use:

HTML
<div></div>
<div class="class1 class2"></div>
<script>
  var e = document.querySelector('.class1');
  console.log(e);
</script>
    

It is also possible to select all elements that match the query:

HTML
<div></div>
<div class="class1 class2"></div>
<script>
  var e = document.querySelectorAll('div');
  console.log(e);
</script>
    
Provide feedback on this page
Comments are sent via email to me.