I had the inclination last week to knock up a quick Javascript function to effectively give you GetElementsByContent. So, you can call a function which returns an array of nodes which match a string (or RegExp) which you pass in, which can optionally be filtered by tag name.
Now, I make no claims that this is “a first”, as it probably isn’t, I wanted to write it, so I did. If I’d have googled it, I’d have probably found something really quickly that did exactly what I wanted and would probably be far superior to what I have written. I wanted to write it for fun really, but I think it’s actually quite useful, so here it is –
var gbc=function(contents,tag){ var n=[];var s=tag||'*'; var b=document.getElementsByTagName(s); var r=new RegExp(contents,'ig'); for(var i=0;i<b.length;i++){ for(var t=0;t<b[i].childNodes.length;t++){ if(b[i].childNodes[t].nodeType==3&&r.test(b[i].childNodes[t].textContent)){ n.push(b[i]); break; } } } return n; }
Because I’m lazy I’ve called it ‘gbc’ (Get By Content), but obviously you can name it whatever you like.
You use it like –
var f = gbc('forums');
This would return all nodes in the current document which contain the text ‘forums’.
You could do –
var f = gbc('forums','a');
This would return all nodes matching the text ‘forums’ (within the text content, not attributes), but limit the search to just ‘a’ tags.
Because the first parameter (the text to search) is actually treated as a regex, you can actually pass it a string to treat as a regex. So –
var f = gbc('abc\\d+');
This would return all nodes which contain the text ‘abc’ followed by one or more numbers. Note the double slash, this is due to the way Javascript interprets the RegExp when using the ‘new’ style syntax, you need to escape any slashes.
That’s about it really, let me know if you use it or have any feedback.
Leave a Reply