Translation: Crazy geek

Original text: medium.freecodecamp.org/an-introduc…

The Javascript DOM (Document Object Model) is an interface that allows developers to manipulate page content, structure, and style. In this article, we’ll understand what the DOM is and how to manipulate it with Javascript. This article can also serve as a reference for basic DOM manipulation.

What is DOM?

Basically, web pages are made up of HTML and CSS documents. The description that the browser uses to create the document is called the Document Object Model (DOM). It enables Javascript to access and manipulate elements and styles on a page. The model is built in an object-based tree structure and defines:

  • HTML elements as objects
  • Attributes and events of HTML elements
  • Methods to access HTML elements

The HTML DOM model

The locations of elements are called nodes. Not only do elements get nodes, but the attributes of elements and text also have their own nodes (attribute nodes and text nodes).

DOM document

The DOM document is the owner of all other objects on the page. This means that if you want to access any object on the page, you have to start here. It also contains a number of important properties and methods that enable us to access and modify our own pages.

Finding HTML elements

Now that we know what a DOM document is, it’s time to get our first HTML element. There are many different ways to use the Javascript DOM, but these are the most common:

Gets the element by ID

The getElementById() method is used to get a single element by its ID. Let’s look at an example:

var title = documentDocument.getelementbyid (" header - the title ");Copy the code

We get the element with id header-title and save it to a variable.

Gets elements by class name

Multiple objects can also be obtained using the getElementsByClassName() method, which returns an array of elements.

var items = documentGetElementsByClassName (' list - the items');Copy the code

Here we get all the items of class list-items and save them to variables.

Gets elements by label name

You can also get elements by tag name using the getElementsByClassName() method.

var listItems = documentThe getElementsByTagName (" li ");Copy the code

Here we take all the Li elements in the HTML document and store them in variables.

Queryselector

The querySelector() method returns the first element that matches the specified CSS selector. This means you can get elements by ID, class, tag, and all the other valid CSS selectors. Here I’ve listed some of the most commonly used options.

Obtain by ID:

Var header = document. QuerySelector ('# header ")
Copy the code

Get by class:

Var items = document. QuerySelector ('. The list - items')Copy the code

Obtain by label:

Var headings = document. QuerySelector (" h1 ");Copy the code

Get more specific elements:

You can also use CSS Selectors to get more specific elements.

documentQuerySelector (" h1. The heading ");Copy the code

In this example, we search for both the tag and the class, and return the first element passed to the CSS Selector.

Queryselectorall

The querySelectorAll() method is exactly the same as querySelector(), except that it returns all elements that match the CSS Selector.

Var heading = document. QuerySelectorAll (' h1 heading ');Copy the code

In this example, we get all the H1 tags belonging to the heading class and store them in an array.

Changing HTML elements

The HTML DOM allows you to modify the content and style of AN HTML element by changing its attributes.

Changes to the HTML

The innerHTML attribute can be used to modify the content of an HTML element.

Document. The getElementById (" # header "). The innerHTML = "Hello World!" ;Copy the code

In this example, we get the element with id header and set its content to “Hello World!” .

InnerHTML can also put a tag inside another tag.

document.getElementsByTagName("div").innerHTML = "

Hello World!

"
Copy the code

Here you put the H1 tag into all existing divs.

Change the value of the property

You can also use the DOM to change the value of a property.

documentGetElementsByTag (" img "). The SRC = "test. JPG";Copy the code

In this example, we changed the SRC of all tags to test.jpg.

Change the style

To change the style of an HTML element, you need to change the element’s style attributes. Here is an example syntax for changing styles:

document.getElementById(id).style.property = new style
Copy the code

Here’s an example where we get an element and change the bottom border to a pure black line:

Document. GetElementsByTag (h1). The style.css. BorderBottom = "solid 3 px # 000;"Copy the code

CSS properties need to be written in CamelCase instead of normal CSS property names. In this example, we use borderBottom instead of border-bottom.

Add and remove elements

Now let’s look at how to add new elements and remove existing ones.

Add elements

var div = documentThe createElement method (" div ");Copy the code

Here we create a div element with the createElement() method, which takes the tag name as an argument and stores it in a variable. All you have to do is give it something, and then insert it into the DOM document.

var content = document.createTextNode("Hello World!"); 
div.appendChild(newContent);
document.body.insertBefore(div, currentDiv);
Copy the code

The content is created using the createTextNode() method, which takes a string as an argument and then inserts a new div element in front of an already existing div in the document.

Remove elements

var elem = document.querySelector('#header');
elem.parentNode.removeChild(elem);
Copy the code

In this case, we take an element and remove it using the removeChild() method.

Replace the element

Now let’s look at how to replace a project.

var div = document.querySelector('#div');
var newDiv = documentThe createElement method (" div "); newDiv.innerHTML ="Hello World2"
div.parentNode.replaceChild(newDiv, div);
Copy the code

Here we use the replaceChild() method to replace the element. The first argument is the new element, and the second argument is the element to be replaced.

Write directly to the HTML output stream

You can also use the write() method to write HTML expressions and JavaScript directly to the HTML output stream.

documentWrite (" < h1 > Hello World!</h1><p>This is a paragraph!</p>");Copy the code

We can also pass parameters like date objects to JavaScript expressions.

document.write(Date());
Copy the code

The write() method can also use multiple parameters that are appended to the document in the order in which they appear.

The event processing

The HTML DOM allows Javascript to react to HTML events. Here are some of the more important events:

  • The mouse to click
  • Page load
  • The mouse moves
  • Input field changes

Distribution of events

You can define events directly in HTML code with attributes on tags. Here is an example of an onclick event:

< h1 onclick ="thisInnerHTML = 'Hello! '" > Click me!</h1>
Copy the code

In this case, when the button is clicked, the text of

will be changed to “Hello!” .

You can also call a function when an event is raised, as shown in the following example.

ChangeText (< h1 onclick ="this) "> Click me!</h1>
Copy the code

Here we call the changeText() method when the button is clicked and pass the element as an attribute.

You can also assign the same event to multiple elements using Javascript code.

documentDocument.getelementbyid (" BTN "). The onclick = changeText ();Copy the code

Specify event listeners

Let’s look at how to assign event listeners to HTML elements.

documentAddEventListener (document.getelementbyid (" BTN ")'click', runEvent);
Copy the code

Here we just specified a click event to call the runEvent method when a BTN element is clicked.

It is also possible to assign multiple events to a single element:

documentAddEventListener (document.getelementbyid (" BTN ")'mouseover', runEvent);
Copy the code

Relationship between nodes

Nodes in a DOM Document have hierarchical relationships. This means that nodes are structured like trees. We use terms such as parent, sibling, and child to describe the relationship between nodes.

The top-level node is called the root node and is the only node without a parent node. The root in a normal HTML document is the < HTML /> tag, because it has no parent tag and is the top tag of the document.

Navigate between nodes

You can navigate between nodes with the following properties:

  • parentNode
  • childNodes
  • firstChild
  • lastChild
  • nextSibling

Here is an example of getting the parent element of h1.

var parent = documentDocument.getelementbyid (" heading "). ParentNodeCopy the code

conclusion

Hopefully this article will help you understand the Javascript DOM and how you can use it to manipulate elements on a page.

If you find this useful, please recommend it to your friends and share it with them.

If you have questions or feedback, let me know in the comments below.

Welcome to pay attention to Beijing cheng Yideng public number: Beijing Cheng Yideng, get more front-end dry goods.