jeudi 9 juillet 2020

If Else statement breaks because variable doesn't always exist

I am creating a custom javascript variable in Google Tag Manager that SHOULD register specific button clicks and pass back another field/title text as a variable.

The issue with the code that I am finding below is that the mapButtonText variable doesn't always exist (you have to click on the map icon for it to exist) until then when I go to the developers console in chrome and look for mapButtonText all I get returned is:

Uncaught TypeError: Cannot read property 'innerText' of null at <anonymous>:1:124

Also, when the else if statement reaches the mapButtonText condition it breaks the entire if else statement (meaning even the first statement won't return the correct value anymore).

function(){
  
  var formButtonText = document.querySelector("#locationSelect > button").innerText;
  var formSelectedLocation = document.querySelector('#locationID option').innerText;
  var mapButtonText = document.querySelector("#map > div > div > div > div > div > div > div > div > div > div > div > div > div.infoWindow > a").innerText;
  var mapSelectedLocation = document.querySelector('.infoWindow:hover h3').innerText;
  var clickLocationName;
  var clickElementText = ;

  if (clickElementText === formButtonText){
    clickLocationName = formSelectedLocation;
  }
  else if (clickElementText === mapButtonText){
    clickLocationName = mapSelectedLocation;
  }
  else {clickLocationName = "No Location Selected";}

  return clickLocationName;

}

I have tested excluding the else if line and the code works fine (see code below)

function(){
  
  var formButtonText = document.querySelector("#locationSelect > button").innerText;
  var formSelectedLocation = document.querySelector('#locationID option').innerText;
  var mapButtonText = document.querySelector("#map > div > div > div > div > div > div > div > div > div > div > div > div > div.infoWindow > a").innerText;
  var mapSelectedLocation = document.querySelector('.infoWindow:hover h3').innerText;
  var clickLocationName;
  var clickElementText = ;

  if (clickElementText === formButtonText){
    clickLocationName = formSelectedLocation;
  }
  else {clickLocationName = "No Location Selected";}

  return clickLocationName;

}

What am I missing in the else if statement to make the first piece of code work?

Aucun commentaire:

Enregistrer un commentaire