Solution 1 :

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>

Problem :

Given this:

function moveRight() {
  var tmp = document.getElementById("lefttext").innerText;

  if (document.getElementById("lefttext").innerText != null) {
    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>

I am trying to make use of two buttons (left, right) to move the placeholder text between the left and right of the table column. Currently, I am testing on one side (moving to the right only) but the method I came up with allow the text to be swapped between the two location instead of just moving it to the right and stop.

Isn’t the “IF” suppose to prevent this if my “lefttext” innerText is null (empty)? What is the correct approach I should take?

Thanks.

Comments

Comment posted by gforce301

There is a difference between

By