Home  >  Article  >  Web Front-end  >  jQuery selector querySelector usage guide_jquery

jQuery selector querySelector usage guide_jquery

WBOY
WBOYOriginal
2016-05-16 16:18:111133browse

Introduction

HTML5 introduces two new methods, document.querySelector and document.querySelectorAll, to Web API to more conveniently select elements from the DOM. Their functions are similar to jQuery's selectors. This makes writing native JavaScript code a lot easier.
Usage

The two methods use similar syntax, and both receive a string parameter. This parameter needs to be a legal CSS selection syntax.

Copy code The code is as follows:

element = document.querySelector('selectors');
elementList = document.querySelectorAll('selectors');

The selectors parameter can contain multiple CSS selectors, separated by commas.

Copy code The code is as follows:

element = document.querySelector('selector1,selector2,...');
elementList = document.querySelectorAll('selector1,selector2,...');

Using these two methods cannot find elements with pseudo-class status. For example, querySelector(':hover') will not get the expected results.

querySelector

Copy code The code is as follows:

element = document.querySelector('div#container');//Return the first div
with the id of container element = document.querySelector('.foo,.bar');//Return the first element with foo or bar style class

querySelectorAll

This method returns all elements that meet the conditions, and the result is a nodeList collection. The search rules are the same as described before.

elements = document.querySelectorAll('div.foo');//Return all divs with foo class style
It should be noted that the elements in the returned nodeList collection are not real-time.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn