As personal project I would like to build a Chrome extension that will find all hashtags on a page. I don't much about JS or jquery so I wonder how I should approach this?
EDIT: The Chrome Extension injects javascript after the page has loa开发者_C百科ded, but I need to scan the whole document for a hashtag. It is looking through the whole document that I am not sure how to do.
Thanks!
If you mean simply anchor tags with a href that has a # in it then:
var aTags = document.getElementsByTagName("a");
for(var index = 0; index < aTags.length; index++){
if(aTags[index].href.indexOf("#") != -1){
alert("found one");
}
}
Or if you want something more general, one way to return the entire webpage is simply:
document.body.innerHTML //A string containing all the code/text inside the body of the webpage.
And then you can do some indexOf or a regex search/replace depending on what you want to do specifically.
But if you know that the hashtag you are looking for is always in some container like a anchor or even just a div with particular class then I would go with that instead of working with the entire page. Here is a list of useful methods to parse up a webpage:
document.getElementsByTagName("a"); //already mentioned
document.getElementsById("id");
document.getElementsByName("name");
//and a custom function to get elements by class name(I did not write this)
function getElementsByClass(searchClass, domNode, tagName)
{
if (domNode == null) domNode = document;
if (tagName == null) tagName = '*';
var el = new Array();
var tags = domNode.getElementsByTagName(tagName);
var tcl = " "+searchClass+" ";
for(i=0,j=0; i<tags.length; i++)
{
var test = " " + tags[i].className + " ";
if (test.indexOf(tcl) != -1)
{
el[j++] = tags[i];
}
}
return el;
}
精彩评论