How can I click a <li> item with Greasemonkey?

久未见 提交于 2019-12-06 16:00:18

问题


<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:


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();


来源:https://stackoverflow.com/questions/10971661/how-can-i-click-a-li-item-with-greasemonkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!