Blog Question Follow-Up: Setting Style Properties

From the TMS Software Blog....

A Question from Czech Tomasz...

Hi,
procedure a();
var progressElem: TJSElement;

begin
progressElem:=document.getElementsByClassName(''progress-bar'');

is it possible set style property for progressElem e.g. width --> 20px
end;

Yes, you can do this. But be careful which "getElement" functions you're using.

getElementsByClassName('progress-bar') will potentially return a set of results, one for each element that has the class progress-bar. You will then have to iterate through this set to make any changes. This returns a TJSHTMLCollection containing TJSNode entries.

getElementByid('progress-bar') might be better choice, as it returns a single item that you can then make changes to. This function returns a TJSElement.

But depending on what you're doing, either may be useful in different scenarios. One way to do this is to reference TJSNode and TJSElement as TJSHTMLElement and then you can use .style.setProperty().

Here's an example. An element on the page has progress-bar included in its list of class values, and also has progress-bar as its HTML element ID. These can be set for TWeb components using the ElementClassName and ElementID properties, respectively, or can be defined in the HTML directly.

procedure TForm1.WebButton1Click(Sender: TObject);
var
  progressbars: TJSHTMLCollection;
  progressbar: TJSHTMLElement;
  i: Integer;
begin
  progressbars := document.getElementsByClassname('progress-bar');
  i := 0;
  while i < progressbars.length do
  begin
    (progressbars.items[i] as TJSHTMLElement).style.setProperty('height','50px');
    i := i + 1;
  end;

  progressbar := document.getElementById('progress-bar') as TJSHTMLElement;
  progressbar.style.setProperty('width','200px');
end;