Question

I use the below code:

const
  HTML_DOC =
    '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">' +
    '<BODY><P id="p1" style="width: 440px; height: 344px; margin: 3px 2px; float: left;">test</P></BODY>' +
    '</HTML>';

procedure TForm1.Button1Click(Sender: TObject);
var
  HTMLTxtRange: IHTMLTxtRange;
  HTMLDocument: IHTMLDocument2;
  HTMLElement: IHTMLElement;
  HTMLStyle: IHTMLStyle;
begin
  WebBrowser1.Navigate('about:blank');
  while WebBrowser1.ReadyState < READYSTATE_COMPLETE do
    Application.ProcessMessages;

  HTMLDocument := WebBrowser1.Document as IHTMLDocument2;
  HTMLTxtRange := (HTMLDocument.body as IHTMLBodyElement).createTextRange;
  HTMLTxtRange.PasteHTML(HTML_DOC);    

  HTMLElement := (HTMLDocument as IHTMLDocument3).getElementById('p1');
  if Assigned(HTMLElement) then
  begin
    HTMLStyle := HTMLElement.style {as IHTMLStyle2};
    Memo1.Lines.Add(HTMLStyle.cssText);  // MARGIN: 3px 2px; WIDTH: 440px; FLOAT: left; HEIGHT: 344px
    Memo1.Lines.Add(HTMLStyle.getAttribute('margin', 0)); // 3px 2px
  end;    
end;

My question is: how can I get a list of available style attributes using DOM collection without manually parsing HTMLStyle.cssText i.e. expected output:

MARGIN
WIDTH
FLOAT
HEIGHT
Was it helpful?

Solution

IHTMLStyle (or its descendants) do not expose that kind of functionality. However, since IHTMLStyle does implement the IDispatch interface, you can try using IDispatch.GetTypeInfo() to get an ITypeInfo interface describing the style object and then iterate through its available properties, using IDispatch.Invoke() to read the value of each property you discover. However, if GetTypeInfo() does not return a viable ITypeInfo, then you are out of luck, and will have to parse the IHTMLStyle.cssText instead.

OTHER TIPS

var win7: ihtmlwindow7;
     css: ihtmlcssstyledeclaration;
begin
  Win7:= (webbrowser1.document as ihtmldocument2).parentwindow as ihtmlwindow7;
  css:= win7.getcomputedstyle(htmlelement as ihtmldomnode);

  for... css.length
   css.item
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top