DOM Tree
Browser Document: DOM Tree
What is an HTML tag considered in the Document Object Model?
View Answer:
Interview Response: Every HTML tag is an object, according to the Document Object Model (DOM). Nested tags are "children" of the one that contains them, and the text included within a tag is also an object. These objects are available via JavaScript and may be used to alter the page. Document.body, for example, is the object that represents the ‹body› tag.
Code Example:
document.body.style.background = 'red'; // make the background red
setTimeout(() => (document.body.style.background = ''), 3000); // return back
alert(document.body); // alerts [object HTMLBodyElement]
How does the Document Object Model represent HTML?
View Answer:
Interview Response: The DOM represents HTML as a tree structure of tags.
Code Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- Parent DIV -->
<div id="parent">
<!-- Child DIV -->
<div id="child"></div>
</div>
</body>
</html>
If the browser encounters malformed HTML, what happens?
View Answer:
Interview Response: If the browser encounters malformed HTML, it automatically corrects it when making the DOM.
Technical Response: When the browser creates the DOM, it immediately corrects any erroneous HTML. The top tag, for example, is always ‹html›. Even though it does not exist in the document, it exists in the DOM since it is created by the browser. The same is true for ‹body›. Browsers automatically process mistakes in the document and close tags when producing the DOM.
Code Example:
<!-- Malformed HTML before DOM generation -->
<p>
Hello
<li>Mom</li>
<li>and</li>
<li>
Dad
<!-- Fixed, After DOM generation -->
<p>
Hello
<li>Mom</li>
<li>and</li>
<li>Dad</li>
</p>
</li>
</p>
Do HTML tables always have a <tbody>
in the DOM?
View Answer:
Interview Response: Yes, that is an intriguing "unique case" when we use tables. They must have the ‹tbody› element according to DOM specifications, however HTML content may omit it. The browser will then immediately generate ‹tbody› in the DOM.
Code Example:
<!-- Before DOM generation -->
<table id="table">
<tr>
<td>1</td>
</tr>
</table>
<!-- Now, After DOM generation -->
<table id="table">
<tbody>
<tr>
<td>1</td>
</tr>
</tbody>
</table>
What are the four most regularly utilized node types?
View Answer:
Interview Response: The four main node types include document, element, text, and comment nodes.
Technical Response: There are 12 different types of nodes. We usually work with four of them in practice. The four major node types are document, element, text, and comment nodes. The document node is the DOM's starting point. The makeup of element nodes include all HTML tags, which we use as the tree's building blocks. We use the comment node to display information in our code, but it does not show in the browser, but JS can read it from the DOM.