Translator: Front-end wisdom

Source: valentinog

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

The text focuses on ** Document Object Model (DOM)** Understanding what DOM manipulation is and how to use the 砶 DOM API to interact with Web pages in JS.

What is DOM?

The DOM(Document Object Model) is an XML-specific but htML-extended application programming interface that defines standards for documents that access and manipulate HTML.

The W3C Document Object Model is a platform – and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of documents. HTML is the standard for getting, modifying, adding, and removing HTML elements.

DOM hierarchical node

The hierarchical nodes of the DOM are commonly referred to as DOM trees. All nodes in the tree can be accessed through scripting languages such as JS, and all HTMlL element nodes can be created, added, or removed.

In DOM hierarchical nodes, pages are represented by hierarchical node diagrams.

  • The entire document is a document node, like the root of a tree.
  • Each HTML element is an element node.
  • The text inside an HTML element is a text node.
  • Each HTML attribute is an attribute node.

When we visit a Web page, the browser parses each HTML element, creating a virtual structure of the HTML document and storing it in memory. The HTML page is then transformed into a tree structure, with each HTML element becoming a leaf node connected to the parent branch. Consider the following Html structure:

<! DOCTYPE html> <html lang="en"> <head> <title>A super simple title! </title> </head> <body> <h1>A super simple web page! </h1> </body> </html>Copy the code

At the top of this structure is a document, also known as the root element, which contains another element: HTML. The HTML element contains a head, which in turn has a title. Then the body contains an H1. Each HTML element is represented by a specific type (also known as an interface) and may contain text or other nested elements:

document (HTMLDocument)
  |
  | --> html (HTMLHtmlElement)
          |  
          | --> head (HtmlHeadElement)
          |       |
          |       | --> title (HtmlTitleElement)
          |                | --> text: "A super simple title!"
          |
          | --> body (HtmlBodyElement)
          |       |
          |       | --> h1 (HTMLHeadingElement)
          |              | --> text: "A super simple web page!"
Copy the code

Every HTML Element comes from Element, but much of it is specialized. We can examine the stereotype to find the “category” to which the element belongs. For example, the H1 element is HTMLHeadingElement:

document.querySelector('h1').__proto__

// Output: HTMLHeadingElement
Copy the code

HTMLHeadingElement is a descendant of HTMLElement:

document.querySelector('h1').__proto__.__proto__

// Output: HTMLElement
Copy the code

At this point, especially for beginners, there may be some confusion about the difference between Document and Window. Here’s how they differ!

The difference between Document and Window

Simply put, Document is an object property of the window. The window object represents the window open in the browser. If the document contains frames (frame or iframe tags), the browser creates a Window object for the HTML document and an additional Window object for each frame. All global functions and objects belong to properties and methods of the Window object.

The difference between:

  1. Window refers to a window. Document refers to the page. Document is a child object of window.

  2. The user cannot change document.location(because this is where the document is currently displayed). However, you can change window.location (replace the current document with another document). Window. location is itself an object, and document.location is not an object.

The Document interface has a number of utility methods, such as querySelector(), which is a method to find HTML elements on a given page:

document.querySelector('h1');
Copy the code

Window represents the current browser, and the following code is equivalent to the above:

window.document.querySelector('h1');
Copy the code

Of course, it’s more common to do it the first way.

The window is a global object that can be accessed directly from any JS code running in the browser. Window exposes a number of properties and methods, such as:

window.alert('Hello world'); // Shows an alert
window.setTimeout(callback, 3000); // Delay execution
window.fetch(someUrl); // make XHR requests
window.open(); // Opens a new tab
window.location; // Browser location
window.history; // Browser history
window.navigator; // The actual user agent
window.document; // The current page
Copy the code

Because these properties and methods are also global, they can also be accessed this way

alert('Hello world'); // Shows an alert setTimeout(callback, 3000); // Delay execution fetch(someUrl); // make XHR requests open(); // Opens a new tab location; // Browser location history; // Browser history navigator; // The actual user agent document; // The current pageCopy the code

Some of these are already familiar, such as the setTimeout() method. For example, window.navigator is useful when we want to know the browser language of the current user:

if (window.navigator) {
  var lang = window.navigator.language;
  if (lang === "en-US") {
    // show something
  }

  if (lang === "it-IT") {
    // show something else
  }
}
Copy the code

Common DOM methods

Access to the node

Document.getelementbyid (idName) document.getelementById (idName) Returns the document element object array. GetElementsByName (name) / / by class to get the elements, Returns the document element object array. GetElementsByClassName (className) / / element accessed by the tag name, returns the document element object array. GetElementsByTagName (tagName)Copy the code

Gets/sets the attribute value of the element:

// Parentheses pass in the attribute name, Return the corresponding properties of the element attribute values. The getAttribute (attributeName) / / incoming attribute name and set the value of the element. The setAttribute (attributeName, attributeValue)Copy the code

Creating a Node Node

Document.createelement ("h3") // Create a text node; document.createTextNode(String); Document.createattribute ("class"); // Create an attribute node.Copy the code

Add a node

AppendChild (Node); // Add a Node to the last element. // Insert newNode elelment.insertBefore(newNode,existingNode);Copy the code

Remove nodes

RemoveChild (Node) returns null element.removechild (Node)Copy the code

Common DOM attributes

Gets the parent node of the current element

// Returns the current element's parent object, element.parentNodeCopy the code

Gets the child nodes of the current element

// Return all child node objects of the current element, only the HTML node element.chlidren // Return many child nodes of the current element, including text, HTML, and attribute nodes. ChilidNodes // returns the firstChild of the current element, element.firstChild // returns the lastChild of the current element, element.lastChildCopy the code

Gets the sibling of the current element

NextSibling: null Element.previousSibling: null element.previousSibling: null element.previoussiblingCopy the code

Gets the text of the current element

// Return all text values of the element, including the HTML code element.innerHTML // Return all text values of the current element and its descendants, just the text content, excluding the HTML code element.innerTextCopy the code

Gets the node type of the current node

// Returns the type of the node in numeric form (1-12) // Common 1: element node, 2: attribute node, 3: text node node.nodeTypeCopy the code

Set the style

// Use style element.style.color= "#eea";Copy the code

DOM manipulation

Each HTML element in the DOM is also a node, which can be found like this:

document.querySelector('h1').nodeType;
Copy the code

Returns 1, which is the identifier of a node of type Element. You can also check the node name:

document.querySelector('h1').nodeName;

"H1"
Copy the code

The above example returns the node name in uppercase. But the most important concept to understand is that we primarily use two types of nodes in the DOM:

  • Element nodes
  • Text node

To create an element node, use the createElement method:

var heading = document.createElement('h1');
Copy the code

Create a text node, possibly with the createTextNode method:

var text = document.createTextNode('Hello world');
Copy the code

We then combine the two nodes and add them to the body:

var heading = document.createElement('h1');
var text = document.createTextNoe('Hello world');
heading.appendChild(text);
document.body.appendChild(heading)
Copy the code

These methods need to be kept in mind and used proficiently when learning Dom manipulation.

Creating and manipulating elements the way we currently do is imperative DOM manipulation. Modern front-end libraries solve this problem by supporting declarative methods, such as JQuery, where we can declare what HTML elements we need and let the library do the rest.

DOM manipulation and jQuery

Most of us might be thinking, why bother with a native method like createElement when we can just use JQ?

Note that jQuery is dying out. Bootstrap 5 will remove it from dependencies, and many other projects are removing it as well. There’s a good reason behind this: The native DOM API provides a number of easy ways to manipulate the DOM like JQ, enough to replace some of jQuery’s common DOM manipulation.

If you just want simple interactions and operations, use plain JS. We can even create our own mini-frameworks to abstract away the most common operations: create elements, append, create text.

conclusion

The DOM is a virtual copy of a web page that the browser creates and keeps in memory. Create, modify, and delete HTML elements. These are “DOM operations.” In the past, we relied on jQuery even for simpler tasks, but today native apis are compatible and mature enough to replace jQuery.

JQuery isn’t going away anytime soon, but every JS developer must know how to manipulate the DOM using the native API. There are a number of reasons for this, additional libraries increase the load time and size of JS applications, not to mention DOM manipulation is also a frequent occurrence in technical interviews.

The most common ways to manipulate the DOM are document.createElement() for creating new HTML elements and document.createTextNode() for creating text nodes within the DOM. Note that.appendChild() is used to attach a new HTML element or text node to an existing element.

While a good understanding of native apis is great, modern front-end libraries also provide undeniable benefits. While it is possible to build large JS applications with “native” JS, sometimes Angular, React, and Vue can help. It is also wise to use JavaScript only for simpler prototypes and small to medium sized applications.

Original: www.valentinog.com/blog/html-t…

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, HERE I recommend a good BUG monitoring tool Fundebug.

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.