JavaScript - evaluate() method

revision:


Category : document

The evaluate() method of the Document interface selects elements based on the XPath expression given in parameters. XPath expressions can be evaluated on both HTML and XML documents..

Syntax :

        evaluate(xpathExpression, contextNode, namespaceResolver, resultType, result)
    

Parameters:

xpathExpression : a string representing the xpath to be evaluated.

contextNode : the context node for the query. It's common to pass document as the context node.

namespaceResolver : a function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the xpath itself, so that they can be matched with the document. The value null is common for HTML documents or when no namespace prefixes are used.

resultType : an integer that corresponds to the type of result XPathResult to return. The following values are possible:

ANY_TYPE (0) : whatever type naturally results from the given expression.
NUMBER_TYPE (1) : a result set containing a single number. Useful, for example, in an xpath expression using the count() function.
STRING_TYPE (2) : a result set containing a single string.
BOOLEAN_TYPE (3) : a result set containing a single boolean value. Useful, for example, an xpath expression using the not() function.
UNORDERED_NODE_ITERATOR_TYPE (4) : a result set
ORDERED_NODE_ITERATOR_TYPE (5) : a result set containing all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.
ORDERED_NODE_SNAPSHOT_TYPE (7) : a result set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.
ANY_UNORDERED_NODE_TYPE (8) : a result set containing any single node that matches the expression. The node is not necessarily the first node in the document that matches the expression.
FIRST_ORDERED_NODE_TYPE (9) : a result set containing the first node in the document that matches the expression.

result : an existing XPathResult to use for the results. If set to null the method will create and return a new XPathResult.

Examples:

            const headings = document.evaluate(
                "/html/body//h2",
                document,
                null,
                XPathResult.ANY_TYPE,
                null
            );
            /* Search the document for all h2 elements.
            * The result will likely be an unordered node iterator. */
              let thisHeading = headings.iterateNext();
              let alertText = "Level 2 headings in this document are:\n";
              while (thisHeading) {
                alertText += `${thisHeading.textContent}\n`;
                thisHeading = headings.iterateNext();
            }
            alert(alertText); // Alerts the text of all h2 elements
        

Practical examples

example: return all elements on the page.

code:
                    <div>
                        <p id="evaluate-1"></p>
                    </div>
                    <script>
                        let items = getElementsByXPath("//*"); // return all elements on the page
                        function getElementsByXPath(xpath, parent){
                            let results = [];
                            let query = document.evaluate(xpath, parent || document,
                                null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
                            for (let i = 0, length = query.snapshotLength; i < length; ++i) {
                                results.push(query.snapshotItem(i));
                            }
                            return results;
                        }console.log(items);
                        document.getElementById("evaluate-1").innerHTML = items;
                    
                    </script>
                

example: get all span elements
Span 1
Span 2
Span 3 Span 4
Span 5 Span 6
Span 7

code:
                    <div>
                        <span class="level1">Span 1</span>
                        <div id="container">
                            <span class="level2">Span 2</span>
                            <div>
                                <span class="level3">Span 3</span>
                                <span class="level3">Span 4</span>
                            </div>
                            <span class="level2">Span 5</span>
                            <span class="level2">Span 6</span>
                        </div>
                        <span class="level1">Span 7</span>
                        <br /><br />
                        <div id="info" style="background-color:#e0b0b0; width:400px"></div>
                    </div>
                    <style>
                        .level1 {color:red;}
                        .level2 {color:blue;}
                        .level3 {color:green;}
                    </style>
                    <script>
                        function GetSpanElements () {
                            var message = "";
            
                            if (document.evaluate) {    // Firefox, Opera, Google Chrome and Safari
                                var container = document.getElementById ("container");
                                var xPathRes = document.evaluate ( 'span', container, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
            
                                message += "The contents of the span elements:<br />";
                                var actualSpan = xPathRes.iterateNext ();
                                while (actualSpan) {
                                    message += "<b>" + actualSpan.innerHTML + "</b><br />";
                                    actualSpan = xPathRes.iterateNext ()
                                }
                            }
                            else {  // Internet Explorer
                                message = "Your browser does not support the evaluate method!";
                            }
            
                            var info = document.getElementById ("info");
                            info.innerHTML = message;
                        }
                    </script>