简体   繁体   中英

Detect a button and then press it in JavaScript

I want to make a function that would detect a button on a web page and then click it. But I want it to click a specific item.

function imready()
{
    var btn = document.getElementsByClassName('text-xxxs mb-02');
    for (var i = 0; i < btn.length; i++)
    {
        if (btn[i].innerText.indexOf('AK-47') > -1)
        {
            console.log('runtime');
            chrome.runtime.sendMessage({ type: 'dontrun', update: 1 }, function (response) {
        });
        btn[i].click();
        pressok();
    }
 }

How do I make it so that the var "btn" should equal to document.getElementsbyClassName('x') and also a different className ('y')?

As far as i understand your question, you can use document.querySelector('.classX.classY') to select the needed button with both classes. That works for the case if you only need one button on the page selected, from your code i assume exactly that.

Quoting from https://stackoverflow.com/a/29366682/10450049

getElementsByClassName() returns anHTMLcollection object which is similar to an array but not really an array so you can't call array methods using the returned value. One hack is to use Array's prototype methods along with.call()/.apply() to pass the returned object as the context.

 var elems = document.getElementsByClassName("royal"); var collapsedElems = document.getElementsByClassName("collapsed"); var earray = Array.prototype.slice.call(elems, 0); var concatenated = earray.concat.apply(earray, collapsedElems); console.log(concatenated)

Demo Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM