From my comment
There is a difference between null
and empty (empty string). Though they are both equivalently “falsey” they are not the same thing. Try logging out document.getElementById(“lefttext”).innerText with console.log and see what you get. You don’t get null
you get an empty string and that is !=
to null
,
You can change your original
if (document.getElementById("lefttext").innerText != null)
to this
if (!!document.getElementById("lefttext").innerText)
The !!
will take care of null
, empty string and undefined
function moveRight() {
var tmp = document.getElementById("lefttext").innerText;
if (!!document.getElementById("lefttext").innerText) {
document.getElementById("lefttext").innerText = document.getElementById("righttext").innerText;
document.getElementById("righttext").innerText = tmp;
}
}
<table width="250px" border="1">
<tr>
<td>
<div id="lefttext">Placeholder</div>
</td>
<td>
<button onClick="moveRight()" id="moveright">Right</button>
<button onClick="moveLeft()" id="moveleft">Left</button>
</td>
<td>
<div id="righttext"></div>
</td>
</tr>
</table>