skip to Main Content

My code wont run the second condition if the value of select is 1
//Not pasted js code

function changeHref() {
    var select = 0;
    const link = document.querySelector("link");

    if (select === 0){
        link.href="css/styleOne.css";
        select = 1;
    } else if (select === 1) {
        link.href="css/styleTwo.css";
        select = 0;
    }
}

I tried to make the conditionals two strings being compared if they have same href values. But now I tried it as var variable that checks if the value is 1 or 0 but I am still not sure why it don’t run. I did not try other attributes of other elements yet thaugh

2

Answers


  1. Because you are always setting select to 0 at the start of your method. You need select to be a global variable instead of a local one. Pass it in as an argument.

    For example,

    function changeHref(selected) {
        const link = document.querySelector("link");
    
        if (selected === 0){
            link.href="css/styleOne.css";
            selected = 1;
        } else if (selected === 1) {
            link.href="css/styleTwo.css";
            selected = 0;
        }
    
       return selected;
    }
    
    Login or Signup to reply.
  2. I am assuming there are only two values of select that is 0 and 1. In that case I will rather change the value of the select to boolean and assign the value of select outside the function.

    In your case the select is initialised inside the function so it is always 0

    let select = true
    
    function changeHref() {
      const link = document.querySelector("link");
      if (select) {
        link.href = "css/styleOne.css";
      } else {
        link.href = "css/styleTwo.css";
      }
      select = !select;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search