element = document.querySelector(selectors);
Returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.
element
is an element object.selectors
is a string containing one or more CSS selectors separated by commas.
In this example, the first element in the document with the class "myclass
" is returned:var
el = document.querySelector(
".myclass"
);
Returns null
if no matches are found; otherwise, it returns the first matching element.
还有一个相对应的方法:
elementList = document.querySelectorAll(selectors);
返回所有匹配的元素,放回结果是一个NodeList。 elementList
is a non-live NodeList of element objects.
Along the lines of other frameworks such as jQuery or Prototype, shortening the "querySelector" name can be convenient.
function $ (selector, el) { if (!el) {el = document;} return el.querySelector(selector); } function $$ (selector, el) { if (!el) {el = document;} return el.querySelectorAll(selector); // Note: the returned object is a NodeList. // If you'd like to convert it to a Array for convenience, use this instead: // return Array.prototype.slice.call(el.querySelectorAll(selector)); } alert($('#myID').id);
Example:
<h1>Test!</h1>
<script>
HTMLDocument.prototype.$ =
function
(selector) {
return
this
.querySelector(selector);
};
alert(document.$(
'h1'
));
// [object HTMLHeadingElement]
</script>
现在所有的元素都有$方法了。