skip to Main Content

I have a problem with React.

I wrote a function:

   function click(event) {
    let element = event.currentTarget.querySelector(".infos__content");
    if (element.style.display) {
        alert("test")
        element.style.display = "none";
    }
    else {
        alert("test1")
        element.style.display = "block";
    }
}

and i called this function successfully in a DIV Container on the "onClick" attribute but it works for just one time, when i click on my div Container again, my if conditional always is true, does anyone know why?

I have google it already but cant find a solution for this

2

Answers


  1. When you are first checking element it will be ”. This will evaluate to false.

    element.style.display
    ''
    

    Then when you assign ‘none’, it will be ‘none’.

    element.style.display='none'
    'none'
    
    element.style.display
    'none'
    

    ‘none’ is a true string value so the expression will always be true. To make your evaluation false you must assign ” or null.

    Login or Signup to reply.
  2. You can also use If statement inside your function to check the current style state of your element and then change accordingly.

    function click(event) {
        let element = event.currentTarget.querySelector(".infos__content");
        if (element.style.display === "block") {
            alert("test")
            element.style.display = "none";
        }
        else {
            alert("test1")
            element.style.display = "block";
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search