JavaScript selector functions querySelector and querySelectorAll

JavaScript selector functions querySelector and querySelectorAll

Selectors are a very powerful feature of Css . Previously, page elements were generally obtained through getElementById and getElementsByTagName , which was very inconvenient in some scenarios.

Later, DOM expanded the Selector API standard, in which Selector API Level 1 included two methods: querySelector and querySelectorAll , which can match page elements through CSS selectors.

1. querySelector queries a single element

querySelector is used to query the first element in the page that meets the rules. It can be called on Document instances and Element instances, receiving a selector string parameter. If it is found, it returns an HTMLElement object, otherwise it returns null .

The syntax format is as follows:

Document instance.querySelector(selector string);

Element instance.querySelector(selector string);

1. Document instance call

Document instance call is to get the matching elements of the entire page.

A simple example is as follows:

// Get the body element let body = document.querySelector("body");

console.log(body)

// Get the element with id container, only the first one will be obtained let container = document.querySelector("#container");

console.log(container)

// Get the element containing btn in class, only the first one will be obtained let btn = document.querySelector(".btn");

console.log(btn);



// Get the element containing btn in the direct subclass of container, only the first one will be obtained let containerBtn = document.querySelector("#container>.btn");

console.log(containerBtn);

2. Element instance call

Element instance call is to obtain the matching elements in the subtree of the element.

Simple example:

// Get the element with ID container let container = document.querySelector("#container");

// Need to check whether the element object exists. Only if it exists, there is a querySelector method if (container) {

	// Only find elements whose class contains btn in the container.

	let containerBtn = container.querySelector(".btn");

	console.log(containerBtn);

}

Theoretically, because CSS can obtain any element on the page through the selector, Element instance call can be directly written as Document instance call method, and you only need to modify the selector string parameter.

For example, the above example can be written directly as follows:

let containerBtn = document.querySelector("#container .btn");

And because there is one less if judgment, the code is more concise. Of course, in some business scenarios, the ELement instance has already been determined, so it is more convenient to call it directly using ELement instance.

2. querySelectorAll queries all elements

The querySelectorAll method is similar to querySelector method, except that it returns all matching elements in NodeList .

Simple example:

// Assume that the page has two div classes containing article

// Get all elements whose class contains article let articleList = document.querySelectorAll(".article");

console.log(articleList);

console.log(articleList.length);

// Console output:

// NodeList(2) [div.article, div.article]

// 2

The querySelectorAll method returns all elements. In practice, traversal is often required. The traversal can be performed using conventional for traversal, for of traversal, and forEach traversal.

// for of traversal for (let item of articleList) {

	console.log(item);

}

// for traversal for (let i = 0; i < articleList.length; i++) {

	console.log(articleList[i]);

	console.log(articleList.item(i));

}

// forEach traverses articleList.forEach((item, index) => {

	console.log(item, index);

});

1. Problems with for in traversal

If for or in traversal is used, some methods on the prototype chain will also be traversed, such as entries , forEach , etc.

2. The problem of snapshots instead of real-time

NodeList obtained using querySelectorAll method is a snapshot, not real-time data.

Consider the following example:

//Use querySelectorAll to obtain, articleList is static, not real-time let articleList = document.querySelectorAll(".article");

console.log(articleList);

console.log(articleList.length); // 2

setTimeout(() => {

	// Add an element let div = document.createElement("div");

	div.className = "article";

	document.body.appendChild(div);	

	console.log(articleList);

	// Still 2

	console.log(articleList.length);

}, 0);

Finally, a timer is set and a div element with class article is inserted into the page, but the length of articleList is still 2.

If getElementsByClassName is used to obtain it, then articleList is real-time data.

Consider the following example:

//Use getElementsByClassName to obtain, articleList is real-time let articleList = document.getElementsByClassName("article");

console.log(articleList);

console.log(articleList.length);



setTimeout(() => {

	// Add an element let div = document.createElement("div");

	div.className = "article";

	document.body.appendChild(div);

	

	console.log(articleList);

	// Here is 3

	console.log(articleList.length);

}, 0);

View the print results in the console:

HTMLCollection dynamic effects:

The object obtained by using getElementsByClassName is of HTMLCollection type and will change with the document flow.

3. Summary

  • 1. querySelector and querySelectorAll get page elements according to CSS selectors, which is very powerful.
  • 2. The elements obtained querySelectorAll are snapshots, static, not real-time. Be careful of pitfalls.

This is the end of this article about JavaScript selector functions querySelector and querySelectorAll For more information about querySelector and querySelectorAll in JavaScript , please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Stay away from JS disasters and CSS disasters: JS private functions and CSS selectors as containers
  • js implements circular menu selector
  • A general discussion on JS logical judgment selectors || &&
  • Understanding Selectors in JavaScript
  • Use iView date picker in Vue.js and set the start time and end time verification function

<<:  Beginner's guide to building a website ⑦: It's so easy to make a beautiful website

>>:  Example code for using HTML ul and li tags to display images

Recommend

Causes and solutions for MySQL deadlock

The database, like the operating system, is a sha...

Organize the common knowledge points of CocosCreator

Table of contents 1. Scene loading 2. Find Node 1...

How to completely delete the MySQL 8.0 service under Linux

Before reading this article, it is best to have a...

MySQL 5.7.15 installation and configuration method graphic tutorial (windows)

Because I need to install MySQL, I record the ins...

Apache Log4j2 reports a nuclear-level vulnerability and a quick fix

Apache Log4j2 reported a nuclear-level vulnerabil...

Docker installation and deployment example on Linux

After reading the following article, you can depl...

Example of using setInterval function in React

This article is based on the Windows 10 system en...

Canvas draws scratch card effect

This article shares the specific code for drawing...

Two methods of restoring MySQL data

1. Introduction Some time ago, there were a serie...

Implementation of Single Div drawing techniques in CSS

You can often see articles about CSS drawing, suc...

Specific use of stacking context in CSS

Preface Under the influence of some CSS interacti...

Two implementation solutions for vuex data persistence

Table of contents Business requirements: Solution...

Detailed process of zabbix monitoring process and port through agent

Environment Introduction Operating system: centos...

Building FastDFS file system in Docker (multi-image tutorial)

Table of contents About FastDFS 1. Search for ima...