Search code examples
javascriptjqueryhtml-parsing

How to find an html element that matches all keywords?


I'm writing a bot-like chrome extension for myself and one of it's functions is to parse a random site for a specific html element that contains all keywords provided by user in custom order and .click() it. I can't do neither of those.

I played around with jQuery's :contains selector a bit and found out that commands like the one i provided below only work for a predefined amount of keywords.

As for .click() problem. For some reason it does not work in my case. This looks strange to me because at the same time '.remove()' works perfectly fine.

Here is my '.js' file responsible for what i'm trying to achieve:

$(document).ready(function() {
    console.log('ready');
    findItem();
});

function findItem() {
    chrome.storage.local.get("settings", function (data) {
        //var newWindow = window.open('SOME SITE URL', 'single');

    if (data.settings.keyWords) {
        
        //code piece that makes an array out of keywords string
        //stored in chrome storage and removes empty elements
        let pkString = data.settings.keyWords;
        const pkArr = pkString.split(", ");
        Object.keys(pkArr).forEach(pk => {
            if (pkArr[pk] == "") {
                pkArr.pop();
                console.log('popped');
            } else {
                console.log(`'${pkArr[pk]}'`);
            }
        });

        if (pkArr) {
            //i basically need something like that but for random amount of keywords
            $(`div:contains("${pkArr[0]}"):contains("${pkArr[1]}"):contains("${pkArr[2]}"):contains("${pkArr[3]}"):contains( ... )`).click();
        }
    }
};

Solution

  • You can map over each keyword and compose this into a single selector like so:

    $(`div${pkArr.map(keyword => `:contains("${keyword}")`).join('')}`).click();
    

    You probably also want to check if there is at least 1 element in the pkArr, otherwise, it will match all <div/> elements on the page.

    As for the click() part, this can be caused by multiple reasons. Either the element is not the correct element or it doesn't have a click event listener attached. Not really sure, but it could also be prevented by the browser.