Search code examples
c#htmlgetelementbyidgetelementsbytagnamewebautomation

Javascript GetElementByName within a C# HtmlDocument


I am writing a web automation that fills out lengthy online forms based on stored data and then notifies the user of the results. The website that I am automating names all of it's objects, but does not use the id tag. Is there something like HtmlDocument.GetElementById that works with the name tag? I don't think GetElementsByTagName is right. It doesn't return the specific element, but instead generates an array.


Solution

  • You can iterate over the elements returned by GetElementsByTagName and check their name attribute (which is not the same as a tag name).

    GetElementByTagName gets all elements that have the same element name (so for images, the tag name is img).

    var inputs = GetElementsByTagName("input");
    
    for(var input in inputs)
    {
      if(input.GetAttribute("name") == nameIAmLookingFor)
      {
        // do something
        break;
      }
    }