Register to get access to free programming courses with interactive exercises

What is DOM? JS: DOM API

To work with JavaScript in a browser, it's important to understand how browsers work, at least in general terms. Let's take any page and consider the basic steps that the browser performs to display it.

Random page

From a bird's-eye view, the process of displaying a page can be represented as follows:

  1. The browser makes a request to the server (having previously found out this address using DNS:

    GET /courses HTTP/1.1
    HOST: ru.hexlet.io
    

    The server sends some HTML code in response.

  2. Once the HTML code is received, the browser begins parsing it and forming an internal structure called a DOM tree

  3. After that, this tree (not the original HTML) is used for the physical rendering of the page that we're looking at right now

The process of page rendering by the browser

What is a DOM tree, and why do we need it to generate a page when we have HTML? The fact is that HTML is just text. It's extremely inconvenient to use it directly (in fact, it's impossible in this case). It's much easier to create an object based on it that will correspond to the structure of the HTML itself. Then use it to generate the page. This object is the DOM tree.

The word tree is used here for a reason. HTML has a tree structure. Tags are embedded in other tags that are embedded in other tags, and so on and so forth. Therefore, the resulting object has the same tree-like structure.

The connection between HTML and DOM

Something similar happens with the source code for JavaScript programs. Text is inconvenient for the interpreter, therefore the code inside JavaScript is first turned into an AST (Abstract Syntax Tree), which is then used to run

The browser forms a DOM tree somewhere inside itself, but it also provides a mechanism for creating a DOM tree directly from JavaScript.

const html = `
  <body>
    <p>hello, <b>world</b>!</p>
  </body>
`;

const parser = new DOMParser();

// Each html tag becomes a node of this tree,
// and the tags nested in it become child nodes.
// Special text nodes are created to represent the text.
// The important thing is that all the elements represented in html 
// go into the DOM tree, including spaces and line feeds.
const doc = parser.parseFromString(html, 'text/html');

// Output the contents of the <body> tag
console.log(doc.body.innerHTML);

The object obtained above has a certain structure that will be the same in all browsers and other programs that work with HTML. That's why it contains the DOM prefix. The Document Object Model is a platform and language-independent format that allows programs and scripts to access the contents of HTML documents, as well as change their contents, structure, and design.

Thanks to the existence of this standard, we're able to write one version of the code for all browsers. Otherwise, if each browser did what it wanted, you would have to write code for each browser individually due to their incompatibility. That's not to say there aren't any differences. Browsers develop at different speeds and don't always keep up with changes in the DOM standard. Therefore, programmers have to wait for new features to appear in the majority of browsers before they can use them. In later lessons, we'll talk about how modern developers deal with these problems using polyfills.

The DOM tree of the current page is available in JavaScript as a document object, which is filled with a large number of methods (according to the DOM specification) for manipulating this tree. Any changes that are made to it are immediately displayed by the browser on the page.

For example:

// The entire page (body tag) will be replaced with this header
document.body.innerHTML = '<h1>For Hexlet!</h1>';

Recovery

Those who have encountered HTML in real life know perfectly well that if you pass erroneous HTML with unclosed tags, broken nesting and other problems to the browser, then there won't be any error messages. The browser will take this HTML and display something on the screen. You may not like what you see, but it will work.

// This HTML contains errors, but the browser will still display it
const html = '</p>hello, hexlet<div>';

The browser really restores the structure of the document and does it according to some very tricky rules. And this is logical, otherwise it would be theoretically impossible to parse. But there is another reason: even if the HTML itself is correct, when creating a DOM tree, the browser adds nodes to it represented by HTML tags. You may have missed this, but the standard requires them to be there. For example, <tbody> is added to the tables, and it doesn't matter whether it was in the original HTML or not.

DOM opens up almost limitless possibilities for changing pages. All libraries (jquery and others) and frameworks (angular, react) manipulate DOM internally. This is the base around which everything in frontend development is built.


Do it yourself

  1. Open the console in your browser.
  2. Use the document object to replace the body of the document (as in the example above) with the following snippet:

    <h1>This is my territory</h1>
    

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.