Jump to content

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);
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;
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...