Search code examples
javascriptdelphitmstms-web-coredelphi-12-athens

How to loop through all html elements that contain a certain class name in TMS WEB Core?


I have a couple of HTML elements on my page that were created dynamically, so my Delphi form doesn't know about them (as far as I'm aware), but all of them have a class attribute called "TestingClass" on the HTML Element. Here's one of them as an example:

<div class="TestingClass">
...
</div>

I'm able to loop through all of them using JavaScript code within Delphi from my form such as:

procedure TfrmMain.Testing(Sender: TObject);
begin
  asm
    const elements = document.querySelectorAll(".TestingClass");
    elements.forEach((element) => {
        console.log(element);
        // Access each element using the "element" parameter
    });
  end;
end;

And that works, but ideally, I'd like to eliminate the JavaScript code and use only Delphi. What would be the equivalent Delphi code to get all elements on my page with that class and then loop through it?

Note that all of these HTML elements are created dynamically using JavaScript. So they don't have the form or application as the owner, but they're all definitely visible on the page and in the DOM.


Solution

  • Okay. I managed to figure it out.

    If you have the WEB unit in your uses, then you can access the document variable and use the following two ways to do it:

    Using document.querySelectorAll

    procedure TfrmMain.Testing(Sender: TObject);
    var
      TestingClass: TJSNodeList;
      I: UInt64;
    begin
      TestingClass := document.querySelectorAll('.TestingClass');
      for I := 0 to TestingClass.length-1 do
      begin
        console.log(TestingClass.item(I));
        // Access each element using "TestingClass.item(I)"
      end;
    end;
    

    Using document.getElementsByClassName

    procedure TfrmMain.Testing(Sender: TObject);
    var
      TestingClass: TJSHTMLCollection;
      I: UInt64;
    begin
      TestingClass := document.getElementsByClassName('TestingClass');
      for I := 0 to TestingClass.length-1 do
      begin
        console.log(TestingClass.Items[I]);
        // Access each element using "TestingClass.Items[I]"
      end;
    end;