Results 1 to 2 of 2

Thread: getElementsByTagName Issue

  1. #1

    Thread Starter
    New Member
    Join Date
    Jun 2017
    Posts
    13

    getElementsByTagName Issue

    Hello!
    I' m having issue finding elements in htlm code.

    Here is my HTML code that i create to understand and test the getElementsByTagName method in VBA.
    HTML Code:
    <html>
    <body>
    
    <td> Id number </td>
    
    <table>
    	<tr>
    		<td> Id number </td>
    		<td> Last name </td>
    		<td> First name </td>
    		<td> Number </td>
    	</tr>
    	<tr>
    		<td> Id number </td>
    		<td> Last name </td>
    		<td> First name </td>
    		<td> Number </td>
    	</tr>
    </table>
    </body>
    </html>
    Using this vba code:

    Code:
    conta = 0
    Set elements = ie.Document.getElementsByTagName("body")
    For Each element In elements
        conta = conta + 1
    Next element
    MsgBox ("") & conta
    I found 1 body element.

    But if i try this one:

    Code:
    conta = 0
    Set elements = ie.Document.getElementsByTagName("tr")
    For Each element In elements
        conta = conta + 1
    Next element
    MsgBox ("") & conta
    The result is 0. Tried also to find the td elements and the result is 0.
    Can't understand.
    Wouldn't getElementsByTagName method give the collection of elements with the given tag present in the body?
    Last edited by Andreaxs; Sep 24th, 2017 at 07:47 AM.

  2. #2
    PowerPoster
    Join Date
    Dec 2004
    Posts
    25,618

    Re: getElementsByTagName Issue

    I found 1 body element
    in the first case, only one element is returned in the collection so the result is correct, to count all the elements within the body you need like
    Code:
    For Each element In elements(0).all
    or in the case where multiple elements could be returned, you would need a double loop
    Code:
    For Each element In elements
        for each ele in element.all
    returned 14

    the second example returned 2 for me which was also correct
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width