How to make this script 'bulletproof'

125 Views Asked by At

I have a script that is failing when calling 'box-tip' [0] index. is there a way to improve/fix this script or make it more bulletproof so that it doesn't break? all suggestions welcome, please view my code below.

var map = {};

var site = util.getCookie('CTCountry').toLowerCase();
if (site === 'gb' || site === 'us' || site === 'xbr' || site === 'eu') {
  map = {
    '14.5': 33,
    '15': 33,
    '15.5': 34,
    '16': 35,
    '16.5': 35,
    '17': 35,
    '17.5': 36,
    '18': 36,
    '19': 37,
    '20': 37
  };
} else {
  map = {
    '37': 84,
    '38': 84,
    '39': 86,
    '41': 86,
    '42': 89,
    '43': 89,
    '44': 91,
    '46': 91,
    '48': 94,
    '50': 94
  };
}

function applyRecommendedSleeveLength(selectedVal) {
  if (selectedVal !== undefined) {
    var recommendedVal = map[selectedVal.trim()];
    var selected = $('.attribute__swatch--selected:first div').text().trim();
    if (recommendedVal === null || recommendedVal === undefined) {
      selectedVal = $('.attribute__swatch--selected:first div').text().trim();
      recommendedVal = map[selectedVal.trim()];
    }
    var sleevSwatches = document.querySelectorAll('[class*="attribute__swatch--length-"] div');
    sleevSwatches.forEach(function(swatch, i) {
      $('showBorder').removeClass('info');
      swatch.classList.remove('showBorder');
      $('.box-tip').hide();
    });

    if (selected === null || selected === '' || selected === undefined) return;

    var recommendedLis = document.querySelectorAll('[class*="attribute__swatch--length-' + recommendedVal + '"] div');
    recommendedLis.forEach(function(recommendedLi, i) {
      if (recommendedLi !== null && recommendedLi !== undefined) {
        recommendedLi.classList.add('showBorder');
        $('.box-tip').show();
        var currentPosition = $('.showBorder').parent().position().left;
        var info = document.getElementsByClassName('box-tip')[0];
        if (info !== null && info !== undefined) {
          info.style.paddingLeft = currentPosition + -75 + 'px';
        }
      }
    });
  }
}

(function() {
  if (typeof NodeList.prototype.forEach === "function") return false;
  NodeList.prototype.forEach = Array.prototype.forEach;
})();

1

There are 1 best solutions below

0
On BEST ANSWER

Specifically for box-tip:

var info = document.getElementsByClassName('box-tip')[0];

This will break if there are no elements with class='box-tip' because you are forcing it to read the first element of that collection even though there might be none. That can be quickly repaired as:

var collection = document.getElementsByClassName('box-tip');
var info = collection.length ? collection[0] : false;
// if there were no elements in the collection info = false;

if (info) {
  info.style.paddingLeft = currentPosition + -75 + 'px' ;
}