Get value of HREF for links within a certain Class in Javascript

Lewis Boyles-White picture Lewis Boyles-White · Sep 1, 2013 · Viewed 16.1k times · Source

I'm trying to process a page to find the value of href's within a certain div class. Please bear in mind I'm not using the class of the <a>.

Here is what I have:

var domains = document.getElementsByClassName('r');
for(var i = 0; i < domains.length; i++){
var hello = document.getElementsByClassName('r')[i].innerHTML;
alert(hello);
}

This works fine and will "alert" the content within the class. (I know this isn't well supported in IE but that's fine).

I get an alert like:

<a href="http://stackoverflow.com/questions/887307/getting-href-value-of-from-a-tag"    onmousedown="return     rwt(this,'','','','1','AFQjCNGsxCA6nMXughTW44nSEa94KtbEaQ','','0CC8QFjAA','','',event)">    <em>javascript</em> - <em>getting href</em> value of from &lt;a&gt; tag - Stack Overflow</a>

What's the best way to get the value within the href?

The HTML is like this:

<h3 class="r"><a onmousedown="return rwt(this,'','','','1','AFQjCNFgNBuo2EfLPoNBi3hGgbuTeLwODw','','0CC8QFjAA','','',event)" href="http://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CC8QFjAA&url=http%3A%2F%2Fwww.w3schools.com%2Fjsref%2Fprop_html_innerhtml.asp&ei=LacjUo4lw9m0BpLVgYAK&usg=AFQjCNFgNBuo2EfLPoNBi3hGgbuTeLwODw&bvm=bv.51495398,d.Yms"> … </a></h3>

Answer

Matt Ball picture Matt Ball · Sep 1, 2013

Use Element.attributes instead of Element.innerHTML. With your HTML you also need to use an inner loop to get <a> children of .r elements:

var domains = document.getElementsByClassName('r');
for(var i = 0; i < domains.length; i++){
    var anchors = domains.getElementsByTagName('a');
    for (var j = 0; j < anchors.length; j++) {
        alert(anchors[j].attributes.href);
    }
}

or you could switch to Element.querySelectorAll() for a nicer querying API:

var anchors = document.querySelectorAll('.r > a');
for (var i = 0; i < anchors.length; i++) {
    alert(anchors[i].attributes.href);
}

Note that I reused the domains variable since there's no reason to keep re-querying the DOM at every loop iteration.