A/B test script for Product Variations

Green Desert Cactus

€ 15 € 10 ,-


Splitting product variations

// We use this to declare the CSS with JavaScript.
let objectStyle = document.createElement("STYLE");
let objectCSS = document.createTextNode(
  "#selectOptions{display: flex;flex-direction: column;}"
);
objectStyle.appendChild(objectCSS);
document.head.appendChild(objectStyle);

// We declaring our variables
selectOptions = document.getElementById("selectOptions");
variant = document.getElementById("variants");
variants = document.querySelectorAll("#variants > option");

// This function filters the options based on a keyword
function groupVariants(options, keyword) {
  var group = [];
  for (option of options) {
    if (option.innerText.includes(keyword)) {
      group.push(option);
    }
  }
  return group;
}

// This function creates a select elements with options wrapped by a label
function createSelect(options, parent, labelName) {
  var newLabel = document.createElement("label");
  var newSelect = document.createElement("select");
  newLabel.appendChild(newSelect);
  var newLabelText = document.createTextNode(labelName + " ");
  newLabel.prepend(newLabelText);
  for (option of options) {
    newSelect.appendChild(option);
  }
  selectOptions.appendChild(newLabel);
}

// Then we call the function to split the green and brown variants
createSelect(groupVariants(variants, "Green"), selectOptions, "Green");
createSelect(groupVariants(variants, "Brown"), selectOptions, "Brown");

// We remove the old select options
variant.parentElement.remove();

Want to learn to run any client-side A/B test with JavaScript?

Get started with my free JavaScript for Optimizers mini-course!