Home>

I want to be able to see the hidden element (This is a test) when I click "test".

I was able to switch to display: none ;, but I can't switch to display: block ;.
(I was able to hide what was displayed, but I was not able to show what was hidden.)

When I look at the developer tools, I don't get any error messages.

When I looked at various sites, I found that I changed it to block to display what was hidden by display: none ;, but it doesn't work.

How can it be resolved? I would appreciate it if anyone could tell me.

Corresponding source code
<p onclick = "testbtn ();">test</p>
    
      This is a test.
  
#test_d {
  display: none;
}
.test_h {
  display: block;
}
function testbtn () {
  const test = document.getElementById ('test_d');
  test.classList.add ('test_h');
}
What I tried

The following CSS worked. (Operation to hide from display)
id = "test_d" does not apply any CSS to display from the beginning.
Also, the HTML and javascript codes have not changed from the above.

/ * Click to hide * /
.test_h {
display: none;
}

  • Answer # 1

    CSS selectors have a priority called "details" in the code presented.#test_dIs better.test_hBecause it is more detailed, if the same property is specified in both rulesets#test_dHas priority.

    To fix it, increase the detail of the latter selector or go to the latter property! importantIs attached.

    # test_d.test_h {
      display: block;
    }
    .test_h {
      display: block! important;
    }

    You can lower the detail of the former selector.

    
    .test_d {
      display: none;
    }

  • Answer # 2

    test.style.displayYou can tell if the display is'block'or'none' by examining.
    Therefore, you should make it as a condition of the if statement. I wrote a part below.
    You should be able to add it to this even when it is a block.

    if (test.style.display =='none') {
      test.classList.add ('test_h');
    }

    (correction)
    I made a mistake in reading a part, so I will correct it. Perhaps it is more appropriate to write int32_t as an answer to the question. I was wondering if I wanted to press the test button to turn it on and off. Also, test_h is not a class, so the code presented is also incorrect. I'm sorry.