how to add condition in variable?

function() {

  var product = productrev || productrev2;

  var productrev = document.querySelector("#checkout > div > div > div.col-sm-7.col-md-7.col-lg-7.col-xl-5.checkout-details-main > div > div:nth-child(5) > div.col-md-6.text-right").innerText;

  var productrev2 = document.querySelector("#checkout > div > div > div.col-sm-7.col-md-7.col-lg-7.col-xl-5.checkout-details-main > div > div:nth-child(6) > div.col-md-6.text-right").innerText;

  return product;

}

if productrev is true it should be returned with the data but if it is undefined it should be returned with productrev2, can anyone correct my variable, please ??

enter image description here

2 answers

  • answered 2021-06-19 06:03 Rudr Thakur

    try this.

    function() {
        
          var productrev = document.querySelector("#checkout > div > div > div.col-sm-7.col-md-7.col-lg-7.col-xl-5.checkout-details-main > div > div:nth-child(5) > div.col-md-6.text-right").innerText;
        
          var productrev2 = document.querySelector("#checkout > div > div > div.col-sm-7.col-md-7.col-lg-7.col-xl-5.checkout-details-main > div > div:nth-child(6) > div.col-md-6.text-right").innerText;
        
          return (productrev ? productrev : productrev2);
        
        }
    

    If you are new to programming concepts like conditional operators and logical operators then go with simple conditional statements like if , else.

    Also to be sure your variables have values inside them I suggest logging them into the console so we have a better idea figuring out what is going wrong.

    To make sure your variables have values inside it wait for the DOM to be constructed by putting your code inside onload listener like follows.

    document.addEventListener("DOMContentLoaded", function(event) { 
     
        var product;
        var productrev = document.querySelector("#checkout > div > div > div.col-sm-7.col-md-7.col-lg-7.col-xl-5.checkout-details-main > div > div:nth-child(5) > div.col-md-6.text-right").innerText;
        
        var productrev2 = document.querySelector("#checkout > div > div > div.col-sm-7.col-md-7.col-lg-7.col-xl-5.checkout-details-main > div > div:nth-child(6) > div.col-md-6.text-right").innerText;
        
        if(productrev){
        product = productrev;
        }
        
        else {
        product = productrev2;
        }
    
        console.log(productrev);
        console.log(productrev2);
        console.log(product);
    
        return product;
        
    });
        
    

  • answered 2021-06-19 07:44 M Shahzeb Raza

    window.onload = () => {
        // put all of your code here
    }