Bootstrap Tables with Elm

Surprises in the DOM

billperegoy
im-becoming-functional
3 min readMay 23, 2017

--

An Unexpected Problem

For my side projects, I often depend upon Bootstrap to provide basic styling of my pages. This gives me reasonable looking designs without writing a single line of CSS. I recently ran into an issue where table formatting techniques I had used in pervious HTML projects didn’t work as expected with pages generated from an Elm application.

Tables Using Bootstrap

I often make use of HTML tables and with Bootstrap, I can add a few classes to the table element and I get a nicely formatted, striped table.

Here’s an example of some HTML for a table.

This markup uses the Bootstrap CSS to produce this table.

Now we have a nicely formatted table with just the addition of a couple classes. Let’s try the same thing with Elm.

Bootstrap Tables with Elm

I wrote this Elm code which I expected to behave exactly like the raw HTML code shown above.

After compiling this code, instead of the beautifully formatted and striped table, I got this ugly and wrongly formatted result.

So What Went Wrong?

This result confused me as other Bootstrap formatting was working perfectly in Elm. After a bit of digging, I realized that Bootstrap applied styles to the <thead> and <tbody> elements. This seemed odd to me as I generally never surround my table head and body sections with these elements. So how did the formatting work in my pure HTML implementation?

Going back and inspecting the code from the original non-Elm HTML, I noticed that even though I didn’t explicitly instantiate these elements, they ended up in my DOM. So it seems that my browser was inserting the <thead> and <tbody> attributes into the DOM even when I didn’t include them in my code. Some google searches conformed that this is normal browser behavior.

However, when a page is rendered using Elm, these DOM elements do not get automatically inserted. In order to get proper formatting, I went back to my Elm code and added the thead and tbody elements. The resulting code looks like this.

If I then recompile that code and look at the results in a browser, everything looks nicely formatted.

Summary

Working with Elm can produce some surprises. When working with static HTML, the browser does some “magic” to add the <thead> and <tbody> elements. However, in the Elm world, the DOM elements are actually created with Javascript level DOM manipulation, therefore we need to explicitly dd these elements. Although I haven’t confirmed this, I suspect we’d see the same issue using any other virtual DOM-based framework (i.e. React).

--

--

billperegoy
im-becoming-functional

Polyglot programmer exploring the possibilities of functional programming.