Article Introduction: The Queryselector () method accepts a CSS query and returns the first descendant element of the matching pattern, or null if no matching element is returned. |
The Queryselector () method accepts a CSS query and returns the first descendant element of the matching pattern, or null if no matching element is returned. Take a look at the following example:
Get the BODY element
var body = document.queryselector ("body");
Gets the element
var mydiv = DOCUMENT.QUERYSELECOTR ("#myDiv") with the ID mydiv;
Gets the first element
var selected = Document.queryselector (". Selected") containing the class selected;
Gets the first image element containing the class button
var img = document.body.querySelector ("Img.button");
When the Queryselector () method applies on the document type, it attempts to start the match pattern from the documentation element. If applied to the element type, the query will only attempt to find a match from the descendant node of the elements.
CSS queries can be complicated or simplified as needed. If there is a syntax error in the query or if there is an unsupported selector, then Queryselector () or throws an error.
The Queryselector () method also accepts the optional second argument, which is a namespace parser, a function that accepts a namespace prefix and returns its associated URI, similar to the following:
var nsresolver = function (prefix) {
switch (prefix) {case
' W3CMM ': Return
' http://www.w3cmm.com ';
Other code here
}
};
The namespace parser is useful for executing queries in XHTML documents that are embedded in other languages such as SVG or MathML, as is the case with XML documents. Namespaces in a CSS query are specified using a single pipe, as follows:
var svgimage = document.queryselector ("Svgsvg", function (prefix) {
switch (prefix) {case
: ' svg ': return
' Http://www.w3.rog/2000/svg ";
}
});
This example returns the first SVG image by looking for elements defined as <svg:svg> in the document. When an SVG namespace prefix is encountered in a query, a namespace resolver function is invoked to determine the URI. Without a namespace parser, an error is thrown because the query engine cannot recognize the SVG namespace prefix.