0

I am unable to find the desired element when I use

 HtmlElementCollection elements = webBrowser1.Document.All.GetElementsByName("username");

The count is always 0. However, it is able to find the element when I iterate the elements using for loop like this:

 foreach (HtmlElement element in elements)
        {
            if (element.Name == "username")
            {
                try
                {

                }
                catch (Exception)
                {

                    throw;
                }
            }
        }

Why is this? I would prefer to get the desired elements in one line instead of writing foreach loops for all of them.

Pejman Kheyri
  • 4,044
  • 9
  • 32
  • 39
user9057272
  • 367
  • 2
  • 5
  • 17
  • How did you check the count? – Teemu Mar 19 '21 at 07:56
  • I checked the count property of the elements variable. – user9057272 Mar 19 '21 at 07:58
  • 1
    Check the `length` property instead. – Teemu Mar 19 '21 at 07:59
  • If you instead write: `var element = webBrowser1.Document.All.GetElementsByName("username").OfType().FirstOrDefault();`, is `element` null? -- Where / when are you running this code? Are you sure the Document(s) is (are) loaded completely? Note that it's (are) loaded asynchronously (the Main Document can contain more sub-Documents). – Jimi Mar 19 '21 at 12:26
  • @Teemu Does `HtmlElementCollection` have a `Length` Property? – Jimi Mar 19 '21 at 12:35
  • @Jimi - Yes. It still shows element as null – user9057272 Mar 24 '21 at 05:40
  • @ Jimi - Going by what you said about the document loading, if I use if(element != null) condition, it eventually finds it and goes inside the if condition. – user9057272 Mar 24 '21 at 05:45
  • Read the notes here: [How to get an HtmlElement value inside Frames/IFrames?](https://stackoverflow.com/a/53218064/7444103) – Jimi Mar 24 '21 at 08:07

0 Answers0