Jump to content
markus_ja

How to reorder HTML elements?

Recommended Posts

Usually the data is coming from a webservice to list cities, for instance. The service should return an array of strings, before rendering we can sort an array alphabetically, and then reverse the order of the sorted items.

var 
  aStr : array of String;
  aStr := ['G','Ga','M','B','A','Ab','N','D','X','C'];
  aStr.Sort;

var populateList := function(arr : array of string): string
begin
    var str := '';
    for var i := 0 to arr.length-1 do
    begin
        str += '<li>' + arr[i] + '</li>';
    end;
    Result := str;
end;

var listEl := w3_createHtmlElement('ul');
    listEl.id := 'listSpelling';
    listEl.innerHTML := populateList(aStr);
    MainContainer1.Handle.appendChild(listEl);

Share this post


Link to post
Share on other sites

I have a custom control, where I can add elements to that list. And a new element should be put in the proper order of my list. That means, I have already DOM elements.

 

What I have done so far is maybe not quite perfect, but it works:

procedure TMyCustomListItems.Sort;
begin
  //sort the internal array, which holds the references of the DOM elements
  FItems.Sort(
    function(aLeft, aRight: TMyCustomListItem): Integer
    begin
      result := CompareInt(aLeft.ItemPos, aRight.ItemPos);
    end);

  //Reorder the DOM elements, based on the array order. 
  for var i:=FItems.Count - 2 downto 0 do
  begin
    //param1 .. new node
    //param2 .. reference node
    FItems[i].Handle.parentNode.insertBefore(FItems[i].Handle, FItems[i+1].Handle);
  end;
end;

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×