...

View Full Version : Resolved Extracting links with class



BatCountry
07-27-2011, 03:11 AM
Hiya!
Trying to figure out how to use javascript to extract all links on a page that have a certain class:

e.g. - extract only links with a class of 'tools', ignore all other links:

<a href="http://www.google.com" class="tools">Search</a>
<a href="http://www.tripod.com" class="grapes">Searched</a>
<a href="http://www.dogpile.com">Searches</a>

Any help would be appreciated, I'm guessing I probably have to use something like getelementbyclass("tools")?

Old Pedant
07-27-2011, 03:52 AM
getElementsByClassName returns a collection, same as getElementsByTagName.

But fair warning: It's not supported in older MSIE versions.

So you might want to use getElementsByTagName instead, esp. if this is something you only do at page start or at least rarely.

jmrker
07-27-2011, 03:56 AM
Try this...


<!DOC HTML>
<html>
<head>
<title> Untitled </title>
<script type="text/javascript">
function show(cl) {
var sel = document.getElementsByTagName('a');
var str = '';
for (var i=0; i<sel.length; i++) {
if (sel[i].className == cl) { str += sel[i].href+'\n'; }
}
alert(str);
}
</script>
<style type="text/css">
.tools { background-Color:orange; font-size:2em; }
.grapes { color:orange; font-size:1.5em; }
</style>

</head>
<body>
<a href="http://www.google.com" class="tools">Search</a>
<a href="http://www.tripod.com" class="grapes">Searched</a>
<a href="http://www.dogpile.com">Searches</a>
<p>
<button onclick="show('tools')">Show Tools</button>
<button onclick="show('grapes')">Show Grapes</button>
</body>
</html>

BatCountry
07-27-2011, 05:43 AM
Thanks Old Pedant!

And especially thanks jmrker - that was exactly what I needed to get started +1rep!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum