What is DOM? – Application and how to manage livestock in JavaScript

If you have just started learning JavaScript, you may have heard the DOM name, but don’t know exactly what. In this article we explain what DOM is and what it is useful. We also look at a few examples of JavaScript code and look at how the elements are selected from an HTML document, how to create elements, how to change in -line CSS styles, and how to respond to events.

What is DOM?

DOM stands for Document Object Model means an object -oriented model. This standard is defined by the World Web Consortium (W3C). In fact, DOM is a programming interface or API that allows us to create, modify or remove elements from HTML, XML and XHTML documents. We can also add events to these elements through DOM to make our web page more dynamic. The DOM standard observes each HTML document as a tree of nodes, each of which is defined as an object or node of a tree that has its own characteristics. Therefore, it can be said that DOM organizes and manages the document elements in a tree structure. Take a look at the HTML code below to better understand the structure of the DOM tree:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>DOM tree structure</title>
  </head>
  <body>
    <h1>DOM tree structure</h1>
        <h2>Learn about the DOM</h2>
  </body>
</html>

Our main HTML document is called Root Node and has a child node equivalent to the <html> element. The <html> element itself consists of two children that are equivalent to the <head> and <body> elements. Both elements have their own children. The following image is another way to visualize this tree from nodes:

What is DOM? - Application and how to manage livestock in JavaScript

The point is that we can access these elements in our HTML document and make changes using JavaScript. Here are some examples of things we can do using DOM using JavaScript.

How to select elements in the HTML document

There are several different methods in this article to select a select in the HTML document: In this article, there are three of these methods:

  • () GetElectbyid
  • () Queryselector
  • () QuerySelectorall

1. Check the method () GeteLmentbyid

IDs in HTML are equal to unique IDs assigned to HTML elements. This means that you can’t have an ID name for two different elements. For example, the following code is incorrect:

<p id="para">This is my first paragraph.</p>
<p id="para">This is my second paragraph.</p>

So you need to make sure you have defined a unique ID for each element, as the example below:

<p id="para1">This is my first paragraph.</p>
<p id="para2">This is my second paragraph.</p>

In JavaScript, we can get an HTML tag by referring to the ID:

document.getElementById("name id")

This code tells the computer to receive the <p> element with the ID called “Para1” and print the element in the console.

const paragraph1 = document.getElementById("para1");
console.log(paragraph1);

What is DOM? - Application and how to manage livestock in JavaScript

If you only want to read the paragraph content, we can use the TextContent feature inside the method () Console.log:

const paragraph1 = document.getElementById("para1");
console.log(paragraph1.textContent);

What is DOM? - Application and how to manage livestock in JavaScript

2. Check the method () queryselector

With this method you can find elements that have one or more CSS Selector (CSS). For example, the following HTML code example has created a class of popular television programs:

<h1>Favorite TV shows</h1>
<ul class="list">
  <li>Golden Girls</li>
  <li>Archer</li>
  <li>Rick and Morty</li>
  <li>The Crown</li>
</ul>

If we want to find the H1 element and print on the console, we can use that tag name inside the Queryselector method:

const h1Element = document.querySelector("h1");
console.log(h1Element);

What is DOM? - Application and how to manage livestock in JavaScript

If we want to target “Class =” List to print a list of the names of the serials we wrote in the console, we use the list code. We use the Queryselector () method. This symbol “. Says to target the class name. But if you want to target an ID, you should use the “#” icon before the ID name:

const list = document.querySelector(".list");
console.log(list);

What is DOM? - Application and how to manage livestock in JavaScript

3. Check the method () queryselectorallall

This method finds all the elements that CSS Selector have and returns a list of all those elements (nodes). If we want to find all the <li> elements in the previous example, we can use the Child Combinator to find all the children of the main class, <ul>. Child Combinator is a type of Selector that all children choose a specific element in the HTML code. Note the following example:

const listItems = document.querySelectorAll("ul > li");
console.log(listItems); 

What is DOM? - Application and how to manage livestock in JavaScript

If we want to print the true elements of <li> with television programs, we can use a Foreach () method to create a loop in Nodelist and print any element:

const listItems = document.querySelectorAll("ul > li");

listItems.forEach((item) => {
  console.log(item);
});

What is DOM? - Application and how to manage livestock in JavaScript

How to add new elements to the HTML document
We can add new elements to the DOM tree using the Document.createelect method. Look at the example below:

<h1>Reasons why I love freeCodeCamp:</h1>

Currently, we only have one <H1> tag on the page, but we want to list the reasons I like FreeCodecamp using the JavaScript under that tag. To do this, we can first create a <ul> element using the document.createelect method. Then we assign this element to a variable called UnoderedList:

let unorderedList = document.createElement("ul");

Next, we need to add that <ul> element using the appendchild () method to the HTML document:

document.body.appendChild(unorderedList);

In this section, we need to add a few <li> elements to the <ul> element using the CreeEelect () method:

let listItem1 = document.createElement("li");

let listItem2 = document.createElement("li");

We can then use the Property or TextContent properties to add text to our list elements:

let listItem1 = document.createElement("li");
listItem1.textContent = "It's free";
let listItem2 = document.createElement("li");
listItem2.textContent = "It's awesome";

Finally, we should use the Appendchild () method to add list elements to our inappropriate list:

let listItem1 = document.createElement("li");
listItem1.textContent = "It's free";
unorderedList.appendChild(listItem1);
let listItem2 = document.createElement("li");
listItem2.textContent = "It's awesome";
unorderedList.appendChild(listItem2);

All of our codes are finally as follows:

let unorderedList = document.createElement("ul");
document.body.appendChild(unorderedList);
let listItem1 = document.createElement("li");
listItem1.textContent = "It's free";
unorderedList.appendChild(listItem1);
let listItem2 = document.createElement("li");
listItem2.textContent = "It's awesome";
unorderedList.appendChild(listItem2);

The output of this code on the web page will be as follows:

What is DOM? - Application and how to manage livestock in JavaScript

How to use Style Properties to Change Internal CSS Styles

The Style feature allows you to change the CSS in your HTML document. With an example, we want to change the H1 text using the Style properties from black to blue. The following example is our HTML code example:

<h1>I was changed to blue using JavaScript</h1>

For this, we must first get the h1 tag using the querySelector method:

const h1 = document.querySelector("h1");

Then we use the h1.style.color code to change the h1 text from black to blue:

const h1 = document.querySelector("h1");
h1.style.color = "blue";

The output of the code in the browser will be as follows:

What is DOM? - Application and how to manage livestock in JavaScript

You can use this style property to change a number of inline CSS styles, including background color, border style, font size, and more.

How to use the addEventListener() method to react to page events

This method allows you to attach an event to an HTML element like a button. In the example below, an alert message appears when the user clicks the button. In this sample HTML code, we have a button element with an id of “btn”:

<button id="btn">Show alert</button>

We can target the btn element using the getElementById() method in JavaScript and assign it to a variable called button:

const button = document.getElementById("btn");

The adEventListener() method takes the event type and the function, where the event type will be a click event and our function will generate an alert message. The following code is the code that adds the event listener to the button variable:

button.addEventListener("click", () => {
 alert("Thank you for clicking me");
});

The complete code that can be used to click the button and display the warning message is as follows:

HTML code

<h1>Click the button and an alert will show up</h1>
<div class="btn-div">
 <button id="btn">Show alert</button>
</div>

CSS code

h1 {
 text-align: center;
}
/*Centers the button*/
.btn-div {
 display: flex;
 justify-content: center;
 align-items: center;
}
/*Button styles*/
#btn {
 border: none;
 padding: 10px;
 font-size: 1.3rem;
 background-color: #003366;
 color: white;
 border-radius: 15%;
 cursor: pointer;
}

JavaScript code

const button = document.getElementById("btn");
button.addEventListener("click", () => {
 alert("Thank you for clicking me");
});

The output of the code in the browser will be as follows:

 

What is DOM? - Application and how to manage livestock in JavaScript

Here, by clicking the “Show alert” button, the following message will be displayed:

What is DOM? - Application and how to manage livestock in JavaScript

How to use DOM in real projects

This article is a brief introduction to some useful DOM methods, but there are many more examples related to the DOM standard and its methods that we have not covered in this article. So if you want to start building JavaScript beginner projects and working with DOM, we suggest you find sample JavaScript beginner projects from internet sources and start practicing and coding.

Conclusion

The points we reviewed in this article are summarized as follows:

  • DOM stands for Document Object Model and is a programming interface that allows us to create, modify or delete elements from an HTML document. We can also add events to these elements to make our web page more dynamic.
  • In JavaScript, you can select elements using methods such as getElementById(), querySelector and querySelectorAll().
  • If you want to add new elements to your html document, you can use the document.createElement() method.
  • You can change the inline CSS styles of elements using the style attribute.
  • If you want to add events to elements such as buttons, you can use the addEventListener() method.

 

© 2022 Created with AloApi Team.