How to set and id, classes or other attributes to HTML elements?

Elements generated with Ocsigen are valid and contain required attributes because they must be given as parameters to functions.

But you know what? You can add some optional attributes to your HTML5 elements to make them shine!

The optional parameter "a" is more or less available for every HTML5 elements functions. This argument is taking a list of attributes compatible with the element.

div ~a:[a_class ["red";"shadow"];
        a_id "the_div";
        a_onclick {{ Dom_html.window##alert(Js.string "hello") }}]
    [pcdata "I'm a div with two classes to describe me (red and shadow), ";
     pcdata "an id to make me unique and an action when you click me."]


The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).

The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id. With js_of_ocaml, it is not a good practice to manipulate elements with their identifier manually setted.

Its parameter is a simple string.

~a:[a_id "identifier"]


The class attribute specifies one or more classnames for an element.

The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.

Its parameter is a list of strings.

~a:[a_class ["blue_button"; "small"]]


The style attribute specifies an inline style for an element. The style attribute will override any style set globally, e.g. styles specified in the header of the page.

Using this attribute to stylish elements is not a good practice. You should rather use an external CSS file.

Its parameter is a string.

~a:[a_style "color: pink; padding: 10px;"]


The title attribute specifies extra information about an element. The information is most often shown as a tooltip text when the mouse moves over the element.

Its parameter is a string.

~a:[a_title "Lorem ipsum dolor sit amet."]


Some attributes allow you to do something when the user do an action. They are many available actions since HTML5.

Its argument is an Eliom event handler:

~a:[a_onclick {{ Dom_html.window##alert(Js.string "hello") }}]

Using these attributes is not a good practice. You should rather use event arrows The complete list of event attributes is in tyxml documentation.


◄ Back to the Quick Howto's