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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With