Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 220
bram Avatar asked Sep 05 '25 19:09

bram


1 Answers

Even though jQuery exposes the :contains pseudo selector, it would be wise to restrict the results first by using the class where possible:

$('.market_listing_item_name:contains("Item | Anodized Navy")')

Narrowing down the initial set of tags to search through improves the performance, otherwise all tags would be considered; also, overlapping tags would match as well.

On more modern browsers you could consider this, based on this answer:

function contains(selector, text) {
    var elements = document.querySelectorAll(selector);
    return [].filter.call(elements, function(element) {
        var contents = element.textContent || element.innerText || '';
        return contents.indexOf(text) != -1;
    });
}

var items = contains('.market_listing_item_name', 'Item | Anodized Navy')

items[0] && items[0].click();
like image 87
Ja͢ck Avatar answered Sep 08 '25 09:09

Ja͢ck