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

Detailed process of compiling and installing Storm on Kylin V10 server

1 Introduction Apache Storm is a free, open sourc...

Advantages and Problems of XHTML CSS Website Design

XHTML is the standard website design language cur...

How to move mysql5.7.19 data storage location in Centos7

Scenario: As the amount of data increases, the di...

JavaScript to achieve lottery effect

This article shares the specific code of JavaScri...

Implementation of single process control of Linux C background service program

introduce Usually a background server program mus...

HTML+CSS implementation code for rounded rectangle

I was bored and suddenly thought of the implementa...

How to build mysql master-slave server on centos7 (graphic tutorial)

This article mainly introduces how to build a MyS...

Vue basic instructions example graphic explanation

Table of contents 1. v-on directive 1. Basic usag...

How to quickly install tensorflow environment in Docker

Quickly install the tensorflow environment in Doc...

How to get the height of MySQL innodb B+tree

Preface The reason why MySQL's innodb engine ...

How to recover data after accidentally deleting ibdata files in mysql5.7.33

Table of contents 1. Scenario description: 2. Cas...

Detailed explanation of simple html and css usage

I will use three days to complete the static page...

Full analysis of web page elements

Relative Length Units em Description: Relative len...

Implementation of waterfall layout in uni-app project

GitHub address, you can star it if you like it Pl...