0

How to check if "Some text value" in element p with Id = "SomeID" is there?

<p id="SomeID" class="error" style="display: none"></p>

<p id="SomeID" class="error" style="display: none">Some text value</p>

Here it is in a function form..

function ElementIdText(Web:TembeddedWB; Id:string):string;
var
  node: string;
begin
  if Assigned(Web.Document) and web.DocumentLoaded then begin
  node:=Web.OleObject.Document.GetElementByID(Id).innerText;
  if not VarIsNull(Node) and not VarIsClear(Node) and not AnsiSameStr(node,'') then
  result:=node;
  end;
end;
  • About your update, I'm not sure since I couldn't duplicate the exact issue in your comment but, IMHO, I believe you'd better; Declare a temporary variant (e.g. 'element') and assign `Web.OleObject.Document.GetElementByID(Id)` to it, then check for `VarIsClear`, that would take care of an invalid 'ID'. Another temporary variant (e.g. 'text') and `text:=element.innerText`, and check for `VarIsNull` on 'text' before assigning to 'result'. – Sertac Akyuz Nov 18 '12 at 18:35

1 Answers1

0

Given

<p id="SomeID" class="error" style="display: none"></p>
<p id="SomeOtherID" class="error" style="display: none">Some text value</p>

To retrieve an attribute, use: 

ShowMessage(WebBrowser1.OleObject.Document.
    GetElementByID('SomeOtherID').getAttribute('style').Display);

will output 'none'.

To get the text of the paragraph you can use this:

ShowMessage(WebBrowser1.OleObject.Document.
    GetElementByID('SomeOtherID').innerText);
Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
  • @Joey - I changed one of your 'ID's: SomeOtherID, maybe it's because of that? – Sertac Akyuz Nov 18 '12 at 17:36
  • Error is thrown if the text is not there but if it is it works. So likely it contains NULL but how to check if it contains it? –  Nov 18 '12 at 17:38
  • @Joey - With XE2 here, I get an empty text for a paragraph having no text. If the ID have been invalid you could check `VarIsClear` on a temporary variant that has been assigned to 'WebBrowser1.OleObject.Document.GetElementByID('SomeID')', if the temporary variant is null you can check `VarIsNull`, otherwise I don't know. The worst case, you can trap the error but not very elegant of course. – Sertac Akyuz Nov 18 '12 at 17:52
  • why should the first code return "none" if the attribute value is "display: none"? (Not knowing what '.Display' is doing) – mjn Nov 18 '12 at 17:57
  • @mjn - It's the display property of the style attribute, put 'block' in the source and it will retrieve 'block', put 'anything' and it will retrieve empty text. But frankly I'm not a DOM expert at all... – Sertac Akyuz Nov 18 '12 at 18:13