Reputation:
I want to browse all the links (of a webpage) that contain a specific attribute (e.g all the "a" tags that has the attribute "title".
How can i do this ?
Upvotes: 0
Views: 63
Reputation: 76408
How about the nodes list that is a default property of the document object document.links
, you can iterate that, like so:
for (var i=0;i<document.links.length;i++)
{
if (document.links[i].hasOwnProperty('title'))
{
linksWithTitle.push(document.links[i]);
}
}
or any variaton on this theme
Edit
I did some digging, perhaps an alternative approach would be using a treewalker:
function byTitle(node)
{
if (node.hasOwnProperty('title'))
{
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_SKIP;
}
function getElementsWithTitle(root)
{
root = root || document.links;
var treeWalker,result;
treeWalker = document.createTreeWalker(root,NodeFilter.SHOW_ELEMENT,byTitle,false);
result = [treeWalker.currentNode];
while(treeWalker.nextNode())
{
result.push(treeWalker.currentNode);
}
return result;
}
There's a lot more to treeWalkers and NodeFilters/NodeLists than this, but this is a nice introduction to the whole concept.
Lastly, if you don't care about IE compatibility: document.querySelectorAll('a[title]');
will do the trick
Upvotes: 0
Reputation: 11352
var links = document.getElementsByTagName('a'),//Or also document.links
withTitle = [];
for(varn=0;n<links.length;n++)
if(links[n].getAttribute('title'))
withTitle.push(links[n]);
Or with jQuery:
var withTitle = $('a[title]');
Upvotes: 3