Introduce function usage: document.querySelector

document.querySelectoris a JavaScript function that allows you to select the first matching element in the document by providing a CSS selector. This function returns the matching element if a match was found, otherwise null. document.querySelectoris a very useful method because it allows you to easily select and manipulate DOM elements with various selectors.

The usage of the function is as follows:

const element = document.querySelector(selector);

where selectoris a string containing CSS selectors for finding and selecting elements.

Here are some document.querySelectorexamples using :

  1. Select elements by tag name:

    const firstParagraph = document.querySelector('p');
    

    This will select the first element in the document <p>.

  2. Select elements by class name:

    const firstElementWithClass = document.querySelector('.my-class');
    

    This will select my-classthe first element in the document with the class name.

  3. Select elements by ID:

    const elementWithId = document.querySelector('#my-id');
    

    This will select my-idthe element with the ID.

  4. Select elements via attribute selectors:

    const firstInputElement = document.querySelector('input[type="text"]');
    

    This will select the first element of type in the textdocument <input>.

  5. Select elements with compound selectors:

    const firstElement = document.querySelector('.my-class.another-class');
    

    This will select the first element in the document with the my-classand class names.another-class

Note that document.querySelectoronly the first matching element is returned. If you want to select all matching elements in the document, you can use document.querySelectorAllthe function. This function returns a NodeList containing all matching elements.

const allElementsWithClass = document.querySelectorAll('.my-class');

Guess you like

Origin blog.csdn.net/m0_57236802/article/details/130287312