Question

When use code below in script always get null for e

var e = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();

But use this command in Chrome console, e could get correct value, why this happens?

Here are full code of js file and html file

test.js

function testClick(xpath){
var e = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();
// var a = e.iterateNext();
if(document.createEvent){
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, false);
    e.dispatchEvent(event);
}
else if(document.createEventObject){
    e.fireEvent('onclick');
}
}


var xpath = "(//a[@href='./detail.html'])[1]";
setTimeout(testClick(xpath), 3000);

html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <script type="text/javascript" src="../js/test.js"></script>
</head>
<body>
    <ul>
        <li class="carmen-li"><a href="./detail.html">1</a></li>
        <li><a href="./detail.html">2</a></li>
        <li><a href="./detail.html">3</a></li>
    </ul>
</body>
</html> 
Was it helpful?

Solution

Problem resolved.

This one, code below, works, seems can not call a method with parameter in window.onload directly.

When call method with parameter in window.onload, it will execute this method before window.onload, so the element didn't complete loading when the method is executing, so it will return null.

function testClickWithParam(xpath){
    var e = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();

    if(document.createEvent){
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, false);
        e.dispatchEvent(event);
    }
    else if(document.createEventObject){
    e.fireEvent('onclick');
    }
}

function testClickLink(){
    var xpath = "(//a[@href='./detail.html'])[1]";
    console.log(window.location.href);
    testClickWithParam(xpath);
}


window.onload = testClickLink;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top