How can I click a
  • item with Greasemonkey?
  • 2019-04-15 10:30发布

    <ul class="myList clearfix" id="thismyList">
        <li class="myBullet" id="answer1">blabla1</li>
        <li class="myBullet" id="answer2">blabla2</li>
        <li class="myBullet" id="answer3">blabla3</li>
    </ul>
    

    In this page, how can I automatically click item blabla2?

    1条回答
    贼婆χ
    2楼-- · 2019-04-15 10:49

    The shortest and most powerful is probably the XPath way (btw - it's one of the few w3 specifications that are actually a very good and helpful read). You can have almost any conditions you want to have.

    var xresult = document.evaluate("//*[text()='blabla2']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    xresult.singleNodeValue.click();
    

    evaluate(), click()

    See this doc to know more about XPath in JavaScript.


    The non-XPath way would be to go through all the nodes manually and search for the first one containing the right text:

    var findElem = function(elems, text) {
        for (var i = 0; i < elems.length; i++) {
            if (elems[i].textContent == text) {
                return elems[i];
            } else {
                var result = findElem(elems[i].children, text);
                if (result != undefined) {
                    return result;
                }
            }
        }
        return;
    }
    
    findElem(document.documentElement.children, "blabla2").click();
    
    查看更多
    登录 后发表回答