javascriptclickgetelementbyidtampermonkey

Is there any way to getElementBy the text content?


I've got a problem I've been stuck with for a while, sorry for spamming the forum a little.

Is there any way I can get an element by it's text content? Here's an example:

<span id="result_5_name" class="market_listing_item_name" style="color: #FFD700;">Item | Anodized Navy</span>

I'm trying to get the element by the text content which is 'Item | Anodized Navy'. Is it possible to do something like:

function getelem {
    var item = document.getElementsByTextContent('Item | Anodized Navy');

    item[0].click();
}

I know this doesn't exist, but it's just so you get the idea. Also, I cannot use by Id or classname, and I can't change the HTML code of the element, so it has to be done with the text content, I don't see another way.

I'd greatly appreciate any feedback,

Thanks!


Solution

  • Well, since you tagged the question with , you could use the :contains selector:

    var item = $(':contains(Item | Anodized Navy)');
    

    Note, however, that this will return every element which contains that text, including the span and all the parent elements of the span. If you'd like to get just the inner-most element (assuming there is only one) just get the last item, like this:

    var item = $(':contains(Item | Anodized Navy)').last();
    

    To do the equivalent without using jQuery, you'd have to implement a function like this:

    function getElementsByText(text) {
        var spans = document.getElementsByTagName('span'),
            results = [];
        for(var i = 0; i < spans.length; i++) {
            var content = spans[i].textContent || spans[i].innerText || '';
            if (content.indexOf(text) != -1)
                results.push(spans[i]);
        }
        return results;
    }
    

    Or possibly like this, depending on exactly what you need:

    function getElementsByText(text) {
        function rec(ele, arr)
        {
            if (ele.childNodes.length > 0) 
                for (var i = 0; i < ele.childNodes.length; i++) 
                    rec(ele.childNodes[i], arr);
            else if (ele.nodeType == Node.TEXT_NODE && 
                     ele.nodeValue.indexOf(text) != -1) 
                arr.push(ele.parentNode);
            return arr;
        }
        return rec(document.body, []);
    }
    

    And then call this function like this:

    var item = getElementsByText('Item | Anodized Navy');
    

    Note also in your code, getelem needs to have () after the function name, like this:

    function getelem() {
        var item = getElementsByText('Item | Anodized Navy');
        ...
    }