Register to get access to free programming courses with interactive exercises

Declarative DOM tree search JS: DOM API

As a rule, in real frontend tasks, you need to manipulate an element or set of elements located somewhere deep down in the DOM tree. Moreover, these elements are often scattered over different parts of it. For example, we can mark a list of files for deletion and then perform the actual action of deleting. If you look at it from the perspective of changing the DOM tree, this task boils down to selecting all the elements that represent files (if we look at it visually), and then deleting them.

Specialized search methods

In such a situation, manually traversing through the tree will be extremely tedious. DOM offers several ways to solve this problem at once. The simplest way to search is to search by ID:

<p id="content">This is a paragraph</p>
const el = document.getElementById('content');

Since, according to the specification, there cannot be two identical id on a page, the getElementById() method always returns one element. On the other hand, there is a chance there may be several tags with the same id in HTML. In this situation, the browser will return the first element it encounters.

If you need to process several elements at once, then a class search is a better option:

// Search the entire tree
// All elements with this class are returned. They can all differ significantly.
const collection = document.getElementsByClassName('row');

// This method allows you to search not only through the whole document,
// but also among the descendants of any element.
el.getElementsByClassName('row');

If necessary, you can search by tag. In practice, this is rare, but it's useful to know about this method:

document.getElementsByTagName('span');

// search for all elements
document.getElementsByTagName('*');

// search among the descendants of el
el.getElementsByTagName('span');

Search by selector

The most universal search method is searching by selector. You may remember that a selector is a rule that allows you to describe a set of elements in a DOM tree.

<ul id="menu">
  <li class="odd"><span>First</span> point</li>
  <li>Second</li>
  <li class="odd"><span>Third</span> point</li>
</ul>
// Returns the first element found with the specified selector
// Searching for an element with id=menu
const ul = document.querySelector('#menu');

// All spans nested in tags with the class .odd
const spans = ul.querySelectorAll('.odd > span');

Both querySelector() and querySelectorAll() methods can be applied to the entire document or to a specific element. The search will also go through all the descendants, as usual.

Useful methods

matches

The predicate el.matches(css) checks whether el satisfies the css selector.

<p class="font-weight">This is Hexlet!</p>
const el = document.querySelector('p');
el.matches('.unknown-class'); // false
el.matches('.font-weight'); // true

closest

The el.closest(css) method searches for the closest element higher up the hierarchy that satisfies the selector. The element itself is also analyzed. If such an element is found, it will be returned, otherwise null will be returned.

<div class="row" id="one">
</div>
<div class="row" id="two">
  <div class="row" id="three">
    <span>where is the closest?</span>
  </div>
</div>
const el = document.querySelector('span');
const ancestor = el.closest('.row');
ancestor.id; // 'three'

XPath

A query language originally developed to navigate through DOM trees in XML. Supported by browsers.

<html>
 <body>
    <div>The first layer
      <span>a block of text in the first layer</span>
    </div>
    <div>Second layer</div>
    <div>Third layer
      <span class="text">the first block in the third layer</span>
      <span class="text">the second block in the third layer</span>
      <span>the third block in the third layer</span>
    </div>
    <span>the fourth layer</span>
    <img />
 </body>
</html>

The XPath path /html/body/*/span/@class will correspond to two elements of the source document in it — <span class="text">he first block in the third layer</span> and <span class="text">the second block in the third layer</span>.

Normally, in everyday work, this doesn't happen when working with DOM, so we're only showing you here for completeness' sake. But if you're working with XML documents, XPath is the main way to navigate through the document.


Recommended materials

  1. MDSN - Documentation on Selectors

Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.