You want something like this
HTML
<span id="result_5_name" class="market_listing_item_name" style="color: #FFD700;">Item | Anodized Blue</span>
<span id="result_6_name" class="market_listing_item_name" style="color: #FFD700;">Item | Anodized Navy</span>
<span id="result_7_name" class="market_listing_item_name" style="color: #FFD700;">Item | Anodized Red</span>
<span id="result_8_name" class="market_listing_item_name" style="color: #FFD700;">Item | Anodized Green</span>
<span id="result_9_name" class="market_listing_item_name" style="color: #FFD700;">Item | Anodized Navy</span>
Javascript
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
function getElementsByText(node, text) {
var results = [];
walkTheDOM(node, function (currentNode) {
if (currentNode.nodeType === 3 && currentNode.nodeValue === text) {
results.push(currentNode.parentNode);
}
});
return results;
}
console.log(getElementsByText(document, 'Item | Anodized Navy'));
Output
[span#result_6_name.market_listing_item_name, span#result_9_name.market_listing_item_name]
On jsFiddle
Additional 1, as we talked about treeWalker
function getElementsByText(node, text) {
var results = [],
treeWalker = document.createTreeWalker(
node,
NodeFilter.SHOW_TEXT, {
acceptNode: function (node) {
return NodeFilter.FILTER_ACCEPT;
}
}, false);
while (treeWalker.nextNode()) {
if (treeWalker.currentNode.nodeValue === text) {
results.push(treeWalker.currentNode.parentNode);
}
}
return results;
}
console.log(getElementsByText(document, 'Item | Anodized Navy'));
On jsFiddle
Additional 2, as we talked about getElementsByTagName('*')
function getElementsByText(node, text) {
var results = [],
tags = node.getElementsByTagName('*'),
tagsLength = tags.length,
tagsIndex,
currentTag,
childNodes,
childNodesLength,
ChildNodesIndex,
currentChildNode;
for (tagsIndex = 0; tagsIndex < tagsLength; tagsIndex += 1) {
currentTag = tags[tagsIndex];
childNodes = currentTag.childNodes;
childNodesLength = childNodes.length;
for (ChildNodesIndex = 0; ChildNodesIndex < childNodesLength; ChildNodesIndex += 1) {
currentChildNode = childNodes[ChildNodesIndex];
if (currentChildNode.nodeType === 3 && currentChildNode.nodeValue === text) {
results.push(currentTag);
}
}
}
return results;
}
console.log(getElementsByText(document, 'Item | Anodized Navy'));
On jsFiddle
Note that these solutions are the same but they are different to all the contains
solutions given here. Because these solutions actually give you the nodes that have a matching text node as a child. The simple markup that I have used does not demonstrate this, but you will soon notice the difference when your markup is highly nested.
And finally here is a jsPerf of these 3 solutions.