Monday, September 15, 2008

Function GetElementsByClassName

Recently I faced with problem that in DOM model there is no function GetElementsByClassName like functions GetElementById or GetElementsByName, so I searched on web for this custom function and found some examples, then I modified it a bit and got such code:

'This function returns all elements found in opened IE page with specified className.
'IE - Internet Explorer object


Function GetElementsByClassName(IE, className)
ReDim Result(0)
Set tags = IE.document.all
For Each tag In tags
If tag.className = className Then
If Result(0) = Empty Then
Set Result(UBound(Result)) = tag
Else
ReDim Preserve Result(UBound(Result)+1)
Set Result(UBound(Result)) = tag
End If
End If
Next
If isEmpty(Result(0)) = False Then
GetElementsByClassName = Result
Else
GetElementsByClassName = Empty
End If
End Function

1 comment:

Anonymous said...

Hi, Андрей Кошкаров

How to use it? I need to get "aaa" as below Demo code from DOM , then output innertext,Thanks
need you help.

e.g.
a class="price">123 /a
div class="img-list clear-fix>
a class="price">aaa /a
a class="price">bbb /a
a class="price">ccc /a
/div


Set Elements2 = Browser("creationTime:=0").Object.document.GetElementsByClassName( Browser("creationTime:=0").Object,"img-list clear-fix").getElementsByTagName("a")
For each Element2 in Elements2
If Element2.className="price" then
print Element2.innertext
End If
next

Function GetElementsByClassName(IE, className)
ReDim Result(0)
Set tags = IE.document.all
For Each tag In tags
If tag.className = className Then
If Result(0) = Empty Then
Set Result(UBound(Result)) = tag
Else
ReDim Preserve Result(UBound(Result)+1)
Set Result(UBound(Result)) = tag
End If
End If
Next
If isEmpty(Result(0)) = False Then
GetElementsByClassName = Result
Else
GetElementsByClassName = Empty
End If
End Function

Powered By Blogger