Hint needed for DOM API and Tables

I’m currently experimenting with creation of tables in html using the DOM API (DOM)

I have this example script as space-lua:


function widget.tabletest ()

  local cols = {}
  local rows = {}
   
  for colnr = 1 ,3 , 1
  do 
      for rownr = 1, 4, 1
      do 
          table.insert(cols, 
              dom.td{ rownr .. " / " .. colnr}
          )
      end

      table.insert(rows, 
           dom.tr(cols)
      )
      cols = {}
  end

  return widget.new{
    display = "block",
    cssClasses = {"domtabletest"},
   
    html = dom.table(rows)
  }
  
end

This works already as expected. Now I want to use different space styles for cells and or rows.

Basically I would use something like that to add a classname:
html = dom.span(class="banana", "this is my text")

However this does not work within my loops, where I create the cols and rows.
Only within the inner loop I am able to attach a classname like this:
dom.td{class="banana", rownr .. " / " .. colnr}

But it does not work like that on the outer loop. E.g. with
dom.tr{class="banana", cols}

I get an Lua error: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’.

Same if I try that within the return statement:
html = dom.table{class=“banana”,rows}

I suspect, it is how the contents of “rows” and “cols” look like, as they are already tables with dom-objects. But I can’t see what’s in there, as “print col” only prints out “{}”

Any hint how to change my script to add html classnames?

Thanks a lot!

You can either set the class attribute after the DOM node was created.

local node = dom.tr(cols)
node.setAttribute("class", "banana")
table.insert(rows, node)

Or add the class to the cols table

cols["class"] = "banana"
table.insert(rows,  dom.tr(cols))

If you look at the code in DOM you will see that if you call dom.tag(spec) the way to insert multiple child nodes is to have the spec be like {child1, child2, child3} or with your class attribute {class="banana", child1, child2, child3} .
But you tried passing in {class="banana", {child1, child2, child3} }. Notice the extra nesting.

Thanks a lot, Felix!

That was exactly the explanation I was looking for :slight_smile: Hopefully now I understand the system.
The part with the extra nesting was exactly what I suspected, but I had no idea to overcome.
And you even gave two solutions to choose from! Great!

At least I could make my example script working now :slight_smile:

Thanks again!