4

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
kobik
  • 21,001
  • 4
  • 61
  • 121
  • I don't see any properties that do what you want. Parsing this with a TStringList is a nobrainer though :) – whosrdaddy Jan 07 '13 at 18:23
  • @whosrdaddy, I've already used `TStringList` to parse it, changed `:` to `=` to maintain a key/value, but I don't like this solution. I was hopping that I've missed something and there is such collection available :/ – kobik Jan 07 '13 at 18:28

2 Answers2

1

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I don't see how iterating through the properties can help in this situation... suppose I find `marginLeft` property. should I assume I have a `margin-top` style attribute? or maybe I didn't understand what you meant. – kobik Jan 07 '13 at 22:17
  • When you find a property, read its value and check if it is empty before using it. – Remy Lebeau Jan 08 '13 at 03:10
0
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
Carl
  • 111
  • 9