Defining variants in JavaScript

You define an array of functions that modify the page(s), one function per variant. When the experiment runs a random variant is assigned to the user and the corresponding function executes and modifies the page.

How variants work

MyTest.variants is an array of functions. Each function describes the DOM changes for one variant.

  • The variant function runs when MyTest.renderVariant() is called, after a variant is assigned to the user.
  • Index 0 is the first variant, often the control/original. It can be an empty function or a baseline function.
  • If a user is excluded from the experiment, MyTest.variant is set to -1 and no variant is rendered.
var MyTest = Object.create(Abrantes);

MyTest.variants = [
  function () { /* control or baseline changes */ },
  function () { document.querySelector(".cta").textContent = "Start free trial"; },
  function () { document.querySelector(".cta").textContent = "Get demo"; }
];

MyTest.assignVariant("MyTest");
MyTest.renderVariant();

You should carefully test all variants, in desktop and mobile, before publishing an experiment. During the testing you can pass the variant number as a parameter to the renderVariant method. For example MyTest.renderVariant(1);

Common DOM patterns

Change text

function () {
  document.querySelector("h1").innerText = "MyTest Variant 1";
}

Change HTML

function () {
  document.querySelector("h1").innerHTML =
    'MyTest <span style="color: red;">Variant 1</span>';
}

Add or remove classes

function () {
  document.querySelectorAll("h1").forEach(function (el) {
    el.classList.add("large-header");
    el.classList.remove("d-none");
  });
}

Set attributes

function () {
  document.querySelectorAll("h1").forEach(function (el) {
    el.setAttribute("data-variant", "MyTest Variant 2");
  });
}

Hide elements

function () {
  document.querySelectorAll("h1").forEach(function (el) {
    el.style.display = "none";
    el.setAttribute("aria-hidden", "true");
  });
}

Swap an image

function () {
  document.querySelectorAll("img").forEach(function (img) {
    var original = "example.jpg";
    var variant = "example-variant.jpg";
    if (img.src.includes(original)) {
      img.src = img.src.replace(original, variant);
      img.removeAttribute("srcset");
    }
  });
}

Tips for clean variants

  • Use specific CSS selectors so you only change what you intend.
  • Check for missing elements before updating them.
  • Keep the control in the base HTML and use an empty control function when needed.
  • For delayed content, or content not yet in the DOM, wrap changes in MyTest.waitFor.
Open waitFor.html →
Open example-functions.js →