PDA

View Full Version : Get attribute value of <a> element that has no ID or class using Access VBA



bjay
08-29-2014, 01:50 PM
Hello all;

I tried searching my question on google but couldn't find an answer I'm looking for, probably because I couldn't phrase it properly in a short sentence. So here I am...

I'm trying to access a webpage through Access VBA code, but having trouble getting the "href" form <a> element that don't have a ID or Class.

Here's the example of html I'm trying to access:

<div class="sub_cat_title">
<a href="/somewebsite.com/somepage.htm">Link name</a>
</div>


Here's the VBA I tried:

Dim col As IHTMLElementCollection
Dim elm As IHTMLElement


Set col = html.getElementsByClassName("sub_cat_title")
For Each elm In col
field3 = elm.getAttribute("href")
field2 = elm.outerText
Debug.Print field2 & ", " & field3
Next


As you can expect it only extract the elm.outerText part (Link name) and ignores the elm.getAttribute("heref"). I don't know how to get to the <a> element.

Can someone please help?

Thank you so much for your time.

BJ:)

bjay
08-29-2014, 04:26 PM
Figured it out (for the benefit of others who may have the same issue):

instead of: elm.getAttribute("href")
use: elm.Children(0).getAttribute("href")

VBEveryday
12-20-2018, 09:18 AM
Figured it out (for the benefit of others who may have the same issue):

instead of: elm.getAttribute("href")
use: elm.Children(0).getAttribute("href")

You are an absolute legend, looked all over the net and finally came across this old post. Thanks from the future!

aicis
07-01-2019, 06:47 AM
was looking for this for two days! Thank you. Could somebody explain why Children(0) though?

OBP
07-01-2019, 11:38 AM
Presumably "Children" is an Access Object or VBA Array which start at (0) and not (1).

aicis
07-01-2019, 07:09 PM
Thanks. I was not clear enough - my question is - why attribute "href" is accessible via children collection/array only? why direct elm.getAttribute("href") does not work?