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>
==is a comparison operator where as=is an assignment operator.Inside the
ifcondition you should be comparing (==), and inside the blocks you should be assigning (=);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?.