Search code examples
delphibrowsermshtml

Find Element by Attributes


How can I find an element by its tag and by specific attributes? This code I've written does find it by its tag, however it can't seem to find it by its attributes.

Why is there such behaviour with this code?

function FindElement(const Tag:String; const Attributes:TStringList):IHTMLElement;
var
  FAttributeName, FAttributeValue:String;
  Collection: IHTMLElementCollection;
  E:IHTMLElement;
  Count:Integer;
  i, j:Integer;
begin
  Collection := (EmbeddedWB1.Document as IHTMLDocument3).getElementsByTagName(Tag);
  for i := 0 to Pred(Collection.length) do
  begin
    E := Collection.item(i, EmptyParam) as IHTMLElement;

    for j := 0 to Attributes.Count-1 do
    begin
      FAttributeName:=LowerCase(List(Attributes,j,0,','));
      FAttributeValue:=LowerCase(List(Attributes,j,1,','));

      if not VarIsNull(E.getAttribute(FAttributeName,0)) then
      begin
        if (E.getAttribute(FAttributeName,0)=FAttributeValue) then
        Inc(Count,1);
      end;

      if Count = Attributes.Count then
      Exit(E);
    end;
  end;
end;

procedure TForm2.Button1Click(Sender: TObject);
var
  Attributes:TStringList;
begin
    Attributes:=TStringList.Create;
    Attributes.Add('id,something');
    Attributes.Add('class,something');
    FindElement('sometag',Attributes);
    Attributes.Free;
end;

Solution

  • E := Collection.item(i, EmptyParam) as IHTMLElement;
    // you should clear the value of matched attributes counter for each element
    Count := 0;
    for j := 0 to Attributes.Count-1 do
      begin
    

    P.S. A little optimization:

    if not VarIsNull(E.getAttribute(FAttributeName,0)) then
    begin
      if (E.getAttribute(FAttributeName,0)=FAttributeValue) then
      Inc(Count,1);
    end else 
      // if any of attributes of element is not found, you can skip to next element.
      break;