Dynamic Styling Using the Element API

You can use the Element API to style elements using dynamic class names or inline styles.

The Element API includes two methods that facilitate styling,

  • getClassList(): Gets the set of CSS class names used for the element.

  • getStyle(): Gets the style instance to manage element inline styles.

Using classLists and classNames

You can use the getClassList method to get a collection of CSS class names used for the element. The returned set can be modified to add or remove class names.

Example: CSS style rules.

CSS

  1. .blue {
  2. background: blue;
  3. color: white;
  4. }

Example: Using the getClassList() method to dynamically modify the class names of an element.

Java

  1. button.setText("Change to blue");
  2. button.addEventListener("click",
  3. e -> button.getClassList().add("blue"));

Example: Using the getClassList method to add and remove classes.

Java

  1. element.getClassList().add("error");
  2. element.getClassList().add("critical");
  3. element.getClassList().remove("primary");
  4. // will return "error critical".
  5. element.getProperty("className");
  • The element.getProperty("className") method gets a set of all classes as a concatenated string.

You cannot modify classList or className properties directly using the setProperty methods.

You can set and get an element’s class attribute using:

  • element.setAttribute("class", "foo bar");: This clears any previously set classList property.

  • element.getAttribute('class'): This returns the contents of the classList property as a single concatenated string.

Using the Style Object

You can set and remove inline styles for an element using the Style object returned by the element.getStyle() method. Style property names can be formatted in Camel case, for example backgroundColor, or Kebab case, for example background-color.

Example: Using the getStyle() method for dynamic inline styling.

Java

  1. Element input = ElementFactory.createInput();
  2. button.setText("Change to the entered value");
  3. button.addEventListener("click",
  4. e -> button.getStyle().set("background",
  5. input.getProperty("value")));

Example: Setting and removing style objects using the element.getStyle() method.

Java

  1. element.getStyle().set("color", "red");
  2. //camelCase
  3. element.getStyle().set("fontWeight", "bold");
  4. //kebab-case
  5. element.getStyle().set("font-weight", "bold");
  6. //camelCase
  7. element.getStyle().remove("backgroundColor");
  8. //kebab-case
  9. element.getStyle().remove("background-color");
  10. element.getStyle().has("cursor");