addClass : Html m -> Html m


#1

I like to have an addClass function which ensures a node has a specific class. Is that possible? What would such a function look like?

Googling around I saw similar questions, but with a you can’t do that, which seems odd: https://stackoverflow.com/questions/38787764/transform-html-dom


#2

The short answer is: add the class when creating the element! Html can’t be modified, only created. In order to do this, you might need to restructure some of your view logic to accumulate the necessary data before returning the HTML.

If you post the code where you’re having the problem, we can give a more concrete example!


#3

The use case is a menu, where all items need to have a specific class. It’s just annoying to have to type that in all the time. But yes, from the my googling that’s what I understood.

Obviously I get it that you can’t modify data, just create new things, so I just wanted to reflect a copy back with a class added. Is even that not possible?


#4

You can, of course, write a helper function :wink:

menuItem : List (Html msg) -> Html msg
menuItem children =
  div [ class "menu-item" ] children

Good question. You can’t even make copies, because the VirtualDom.Node is an opaque type. The type is exposed, but the single constructor is not! This is used by libraries to keep data hidden, in order to abstract away an implementation.

For example:

module Foo exposing (Bar, Beep(..)) -- Bar's type is exposed, while Beep's type and constructors are exposed

type Bar = Bar String

type Beep = Beep Int

Here, Bar is opaque, because no other module can create or “open” the Bar value. (Usually, these kind of types will contain more complex types than just a String or Int)


#5

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.