📅  最后修改于: 2023-12-03 14:42:26.632000             🧑  作者: Mango
JavaScript QuerySelector is a method used to select HTML elements based on their tag name, class name, or ID. It is one of the most commonly used methods in JavaScript. In this article, we will be discussing the different ways to use QuerySelector in JavaScript.
The syntax for QuerySelector is as follows:
document.querySelector(selector);
Here, document
refers to the document object and selector
refers to the CSS selector that you want to use.
To select all the elements with a particular tag name, you need to pass the tag name as the selector. For example, to select all the input
elements on a page, you can use the following code:
var inputs = document.querySelectorAll('input');
To select an element by its ID, you need to pass the ID selector. For example, to select an element with the ID username
, you can use the following code:
var username = document.querySelector('#username');
To select all the elements with a particular class name, you need to pass the class name selector. For example, to select all the elements with the class name btn
, you can use the following code:
var buttons = document.querySelectorAll('.btn');
You can also select nested elements using QuerySelector. For example, to select all the li
elements inside a ul
element with the ID myList
, you can use the following code:
var listItems = document.querySelectorAll('#myList li');
If you only want to select the first matching element, you can use the querySelector
method instead of querySelectorAll
. For example, to select the first input
element on the page, you can use the following code:
var input = document.querySelector('input');
JavaScript QuerySelector is a very useful method to select HTML elements. It offers a lot of flexibility in terms of selecting elements based on their tag name, class name, or ID. We hope this article has provided you with a better understanding of how to use QuerySelector in JavaScript.