• 13 JavaScript Methods Useful For DOM Manipulation
  • Original author: Milos Protic
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: fireairforce
  • Proofreader: ZavierTang, smilemuffie

introduce

DOM (Document Object Model) is the basis of all objects on web pages. It describes the structure of the document and provides an interface for the programming language to manipulate the page. It is constructed as a logical tree. Each branch ends with a node, and each node contains child nodes. There are many DOM apis, and in this article, I’ll cover just a few that I find most useful.

document.querySelector / document.querySelectorAll

The document.querySelector method returns the first element in the document that matches the given selector group.

Document. QuerySelectorAll return given selector is set to match with the list of the elements in the document.

Return the first element
const list = document.querySelector('ul');
// Return all div elements with class names intro or warning
const elements = document.querySelectorAll('div.info, div.warning');
Copy the code

document.createElement

This method creates an HTMLElement with the given tag name. The return value is the newly created element.

Node.appendChild

Node.appendchild () this method adds a Node to the end of the list of children of a given parent Node. Note that if the child node given to be added is a reference to an existing node in the document, it will be moved to the end of the child node list.

Let’s take a look at these two methods in action:

let list = document.createElement('ul'); Create a new ul element
['Paris'.'London'.'New York'].forEach(city= > {
    let listItem = document.createElement('li');
    listItem.innerText = city;
    list.appendChild(listItem);
});
document.body.appendChild(list);
Copy the code

Node.insertBefore

This method inserts the given node (and returns the inserted node) before specifying a child node within the parent node. Here is a pseudocode that uses this method:

  1. Paris
  2. London
  3. New York

left

Node.insertBefore(San Francisco, Paris)

left

  1. San Francisco
  2. Paris
  3. London
  4. New York
let list = document.querySelector('ul');
let firstCity = list.querySelector('ul > li'); // We could use list.firstChild here, but the purpose of this article is to introduce the DOM API
let newCity = document.createElement('li');
newCity.textContent = 'San Francisco';
list.insertBefore(newCity, firstCity);
Copy the code

Node.removeChild

The node.removechild method removes child nodes from the DOM and returns the deleted Node. Note that the returned node is no longer part of the DOM, but is still stored in memory. If not handled properly, memory leaks may result.

let list = document.querySelector('ul');
let firstItem = list.querySelector('li');
let removedItem = list.removeChild(firstItem);
Copy the code

Node.replaceChild

This method is used to replace the child node in the parent node (and returns the replaced child node). Note that if not handled properly, this method can cause a memory leak just like Node.removechild.

let list = document.querySelector('ul');
let oldItem = list.querySelector('li');
let newItem = document.createElement('li');
newItem.innerHTML = 'Las Vegas';
let replacedItem = list.replaceChild(newItem, oldItem);
Copy the code

Node.cloneNode

This method is used to create a copy of the given node on which the method was called. This is useful when you need to create a new element on the page that is identical to an existing element. It takes an optional Boolean parameter that indicates whether to deep-clone the child node.

let list = document.querySelector('ul');
let clone = list.cloneNode();
Copy the code

Element.getAttribute / Element.setAttribute

The element. getAttribute method returns the value of the given attribute on the Element, and the corresponding element. setAttribute method sets the value of the attribute on the given Element.

let list = document.querySelector('ul');
list.setAttribute('id'.'my-list');
let id = list.getAttribute('id');
console.log(id); / / output my - the list
Copy the code

Element.hasAttribute / Element.removeAttribute

The element. hasAttribute method checks whether a given Element has the specified attribute. The return value is of Boolean type. Also, by calling element.removeAttribute, we can remove the attribute with a given name from the Element.

let list = document.querySelector('ul');
if (list.hasAttribute('id')) {
    console.log('list has an id');
    list.removeAttribute('id');
};
Copy the code

Element.insertAdjacentHTML

This method parses the rendered text into HTML and inserts the HTML element node into the DOM tree at the given location. It does not break existing nodes in the new HTML element to be inserted. The insertion position can be one of the following strings:

  1. beforebegin
  2. afterbegin
  3. beforeend
  4. afterend
<! -- beforebegin -->
<div>
  <! -- afterbegin -->
  <p>Hello World</p>
  <! -- beforeend -->
</div>
<! -- afterend -->
Copy the code

Ex. :

var list = document.querySelector('ul');
list.insertAdjacentHTML('afterbegin'.'<li id="first-item">First</li>');
Copy the code

Note that when using this method, we need to properly format the given HTML element.

Conclusion and learn more

I hope you found this article helpful and that it will help you understand DOM. Handling the DOM tree correctly is very important, and it can have some serious consequences if used incorrectly. Make sure you always clean up memory and properly format HTML/XML strings.

To learn more, check out the official W3C page.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.