3

I am trying to build a toggle switch which on click add or removes white-space wrap.

The div that has to wrap cannot have and ID, so it needs to be identified via it's class. In this case 'text'. On the entire page, that class only gets used once.

I build this, but it doesn't work. Where do I go wrong?

<script>
function togglew(){    
     if(document.getElementsByClassName("text")[0].style.whiteSpace == 'nowrap'){
      document.getElementsByClassName("text")[0].style.whiteSpace == 'normal';
     }else{
        document.getElementsByClassName("text")[0].style.whiteSpace == 'nowrap';
     }
}
</script>

<a onclick="togglew('');">toggle wrap button</a> 
<br>---<br>
<div style="width:500px;">
    <div class="text" style="overflow:auto;white-space:wrap">ssssssssssd fdfsdfsdf sdf sdf sdf sfd sdf sdf sdf ssdfdddddddddddf sdf sdf sdf sdfsd fsdf sdfsdf sdf sdfsd f</div>
</div>
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
Mr.Boon
  • 2,024
  • 7
  • 35
  • 48

1 Answers1

4

== is a comparison operator where as = is an assignment operator.

Inside the if condition you should be comparing (==), and inside the blocks you should be assigning (=);

if(document.getElementsByClassName("text")[0].style.whiteSpace == 'nowrap')
{
    document.getElementsByClassName("text")[0].style.whiteSpace = 'normal';
} else {
    document.getElementsByClassName("text")[0].style.whiteSpace = 'nowrap';
}

For completeness, there is also the === comparison operator, which also checks that the operators are of-the-same type (== does type coercion if the operands are of different types). For more info, see Which equals operator (== vs ===) should be used in JavaScript comparisons?.

Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180
  • Hi Matt, that worked great! There is still an issue with IE, i get an error there saying: Object doesn't support this property or method. Any idea what is going wrong? In FF and Chrome it works fine. – Mr.Boon Jan 21 '12 at 11:56
  • @Boon: `document.getElementsByClassName` is [not supported in IE < 9](http://caniuse.com/#search=getElements) – Matt Jan 21 '12 at 12:09
  • @Boon IE is a headache (more like a migraine) this is one of the major benefits of libraries – T I Jan 21 '12 at 12:12