Skip to content

Instantly share code, notes, and snippets.

@vmysla
Created April 3, 2015 23:17
Show Gist options
  • Save vmysla/8f040c6aa19a2635a2d5 to your computer and use it in GitHub Desktop.
Save vmysla/8f040c6aa19a2635a2d5 to your computer and use it in GitHub Desktop.
jQuery Lookup element by text
function isTextNode(node){ return node.nodeType == 3 };
function hasTextContent(node, text){ return node.textContent.indexOf(text) >= 0 };
function hasTextNode(element, text){
return $(element).contents().filter(function(i,node){
return isTextNode(node) && hasTextContent(node, text);
}).length > 0;
}
function hasTextAttribute(node, text){
var $node = $(node);
return ($node.val() || '').indexOf(text) >= 0
|| ($node.attr('title') || '').indexOf(text) >= 0
|| ($node.attr('alt') || '').indexOf(text) >= 0;
}
function findTextContainer(text){
return $(':contains('+text+'), [alt='+text+'], [title='+text+'], [value='+text+']')
.filter(function(i, element){
return hasTextNode(element, text) || hasTextAttribute(element, text)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment