Passing Params 2

looks for elements with class cta-button and appends current URL parameter called sessionId

by Ian Roberts

JavaScript

// es6 IIFE
{
  // grab the query string if it exists
  const searchString = window.location.search
  // use the constructor URLSearchParams() to create a new URLSearchParams object
  // see: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams
  const searchParams = new URLSearchParams(searchString)
  // use get() to target parameter named twSessionId, will return null if not present
  const twSessionString = searchParams.get(`twSessionId`)
  // create an array like object
  let elements = document.getElementsByClassName('cta-button')
  // vanilla JS document ready
  document.addEventListener("DOMContentLoaded", function(){
    // check that twSessionString is a string
    if (typeof twSessionString === 'string' || twSessionString instanceof String) {
      // use the array like object as an array by calling Array.prototype.forEach.call
      Array.prototype.forEach.call(elements, function(element) {
        // modify the href of our CTA buttons
        element.href = `${element.href}?twSessionId=${twSessionString}`;
      });
    }
  });
}