Theming in JavaScript

Last updated on
12 October 2025

Drupal provides a theming mechanism for JavaScript code in a similar manner to the way theming works within the rest of Drupal. This lets themes customize the markup generated by JavaScript.

Modules provide theme functions for their markup. For example, the following code provides the theme function powered which displays a "powered by Drupal" icon:

Drupal.theme.powered = (color, height, width) =>
  `<img src="/misc/powered-${color}-${height}x${width}.png" />`;

When a module wants to insert the markup it might do this:

document.querySelector('.footer')
  .insertAdjacentHTML('beforeend', Drupal.theme('powered', 'black', 135, 42));

That will find any elements with the class footer and place an image in them with the following markup:

<img src="http://drupal.org/misc/powered-black-135x42.png" />

When a theme wants to provide different markup it can do so by providing its own theme function. Continuing our example, the following function overrides an existing JavaScript theme function when added by a theme.

Drupal.theme.powered = (color, height, width) =>
  `<div class="powered-${color}-${height}x${width}"></div>`;

If you now try this again:

document.querySelector('.footer')
  .insertAdjacentHTML('beforeend', Drupal.theme('powered', 'black', 135, 42));

You'll get:

<div class="powered-black-135x42"></div>

JavaScript theme functions are entirely free in their return value. They can vary from simple strings to complex data types like objects, arrays, and jQuery elements. Refer to the original (default) theme function to see what your custom theme function should return.

Help improve this page

Page status: No known problems

You can: