Padding params

by Ian Roberts

JavaScript

// es6 IIFE
{
  // grab the last bits of the URL after the ? 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 only target parameter named session, will return null or undefined if not present
  const sessionString = searchParams.get(`sessionId`)
  // create an array like object
  let elements = document.getElementsByClassName('cta-button')

  // vanilla JS document ready
  document.addEventListener("DOMContentLoaded",function(){
    // console.log(`vanilla document ready`)
    // check that sessionString is truly a string
    if (typeof sessionString === 'string' || sessionString instanceof String) {
      //console.log(`//`)
      //console.log(elements)
      //window.els = elements

      // use the array like object as an array by calling Array.prototype.forEach.call
      Array.prototype.forEach.call(elements, function(element) {
        //console.log(element)
        element.href = `${element.href}?sessionId=${sessionString}`;
      });
      // this works in the browsers console but not is javascript loaded by the browser
      // Array.from(window.els).forEach(function(element, index, array) {
      //   console.log(element)
      // });
      // Array.from(elements).forEach(function(element, index, array) {
      //   console.log(element.href = element.href + sessionString)
      //   console.log(element)
      //   console.log(index)
      //   console.log(sessionString)
      //   element.href = element.href + sessionString;
      // });
    }
  });
}