2 Replies - 548 Views - Last Post: 29 May 2018 - 03:50 PM

#1 aemaeth   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 10-February 17

if/else statements ignores first condition even though true?

Posted 28 May 2018 - 10:56 PM

Hey guys, I'm teaching myself Javascript despite already having learned C++ and Java at university. I am making a simple Toggle Accordion news header, that is , just a button that you click that toggles between displaying a div (display: block) or not display the div (display : none), the code is pretty straight forward:
#panel {
  background-color: orange;
  display: none;
}

  </style>
<button onclick="toggleNews()" class="accor">Click Me!</button>

<div id="panel">
Sample Text
</div>



The part that is weird to me is in my Javascript code, when I write the if/else statement like this, it ignores my first if statement completely and executes the else condition, even though the if condition was true:
<script>
function toggleNews() {

var x = document.getElementById("panel");

if (x.style.display === "none") {
  x.style.display = "block";
  }
else 
  {
   document.write("wtf");
   }
}
</script>



So the output will be "wtf", but I have the CSS set to display: none by default, so the if should executate and toggle to "display: block" but it never does... it just keeps document writing out "wtf".

I got it to work by changing the else to x.style.display = "none"; but I still don't get why putting document write in the else condition makes the code not work.

Is This A Good Question/Topic? 0
  • +

Replies To: if/else statements ignores first condition even though true?

#2 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4219
  • View blog
  • Posts: 13,353
  • Joined: 08-June 10

Re: if/else statements ignores first condition even though true?

Posted 28 May 2018 - 11:35 PM

Quote

when I write the if/else statement like this, it ignores my first if statement completely and executes the else condition

That's because CSS rules from a stylesheet are not stored in the style property. cf. https://developer.mo...MLElement/style

Quote

I got it to work by changing the else to x.style.display = "none";

That's because through the assignment the property returns a truthy value.

Quote

but I still don't get why putting document write in the else condition makes the code not work.

That's what document.write() does. if the document is not open (i.e. currently loading), it will create a new document. cf. https://developer.mo.../Document/write
Was This Post Helpful? 0
  • +
  • -

#3 aemaeth   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 10-February 17

Re: if/else statements ignores first condition even though true?

Posted 29 May 2018 - 03:50 PM

Thank you.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1