XPathResult not getting first result Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of XPathResult not getting first result without wasting too much if your time.

The question is published on by Tutorial Guruji team.

When I run the below JS only P elements with hello in it will appear except the first one, why won’t the first one show up?

JS:

        queryResult = 1;

    function testQuery() {
        queryResult = "hello";
        if (queryResult == "") {
            return false;
        }
        $("p").css("display", "none");
        var headings = document.evaluate("//p[contains(., '" + queryResult + "')]", document, null, XPathResult.ANY_TYPE, null);
        var thisHeading = headings.iterateNext();
        while (thisHeading) {
            var thisHeading = headings.iterateNext();
            $(thisHeading).css("display", "block");

        }
    }

html:

<body onload="testQuery();">
    <p>hello</p>
    <p>hello</p>
    <p>goodbye</p>
    <p>hello there</p>
    <p>goodbye friend</p>
</body>

Answer

Just in terms of returning the correct <p> nodes, try changing the relevant part of your code to:

queryResult = "hello";
exp = `//p[contains(., "${queryResult}")]`
var headings = document.evaluate(exp, document, null, XPathResult.ANY_TYPE);

while(thisHeading = headings.iterateNext()) {
  console.log(thisHeading);
}

Output should be the 3 relevant <p> nodes.

We are here to answer your question about XPathResult not getting first result - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji