Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How to know if an element is empty?

I'm making a Tic-Tac-Toe game. My problem is that my code allows to rewrite X or O even if one of the squares already contain X or O. I'm using an if statement to write either X or O depending on a number variable that increases by one every time. I would like to add another conditional that only allows X or O to be written if my tag is empty. How do i do this?. Note: Only javascript please, since I haven't started learning jQuery yet. Thanks a bunch in advance!

JS

var tds = document.querySelectorAll("td");
var player = 1;
var str = "";

for (var i = 0; i < tds.length; i++) {
  tds[i].addEventListener("click", function(){
     if( player % 2 === 0 && tds[i] !== "<td>X</td>"  && tds[i] !==
     "<td>O</td>"){
       this.textContent = "O";
     } else if (player % 2 !== 0 && tds[i] === "" ) {
       this.textContent = "X";
     }
   player++;

  });
}

HTML -

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css.css">
    <title></title>
  </head>
  <body>
    <table>
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </table>
    <script type="text/javascript" src="js.js">

    </script>
  </body>
</html>
like image 693
DannyArcher Avatar asked Nov 23 '17 04:11

DannyArcher


People also ask

How do you know if an element is empty?

This method can be used on this element to test if it is empty by using “:empty” selector. The “:empty” selector is used to select all the elements that have no children. It will return true if the element is empty, otherwise, return false.

How do you check if an element is empty in JS?

To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.

Is Empty function in JavaScript?

The empty statement is a semicolon ( ; ) indicating that no statement will be executed, even if JavaScript syntax requires one. The opposite behavior, where you want multiple statements, but JavaScript only allows a single one, is possible using a block statement, which combines several statements into a single one.

Is empty string null in JavaScript?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.


2 Answers

You could just check the childNodes property of an element, which returns a Nodelist.

If it's length is 0, then your element is empty.

const elem = document.querySelector("#container")
console.log(elem.childNodes.length)
<div id="container"></div>

Careful as line breaks count as text though.

like image 132
nicholaswmin Avatar answered Oct 04 '22 01:10

nicholaswmin


node.childNodes.length will pick up spaces or other elements inside the node you're checking, to include any spacing or returns from formatting.

e.g. The following returns 3

<td>
  <!-- returns NodeList(3) [text, comment, text] -->
</td>

<span>&nbsp;<span> will result in 1 and <span>&nbsp;<span>&nbsp;</span></span> will result in 2 with the above method.

Unless you're sure of your data or cleansing your data source well, I'd use the following to test against node emptiness.

// <div id="SomeElement" />

function isEmpty(node) {
  return node.textContent.trim() === "";
}

isEmpty(SomeElement);

// or

Element.prototype.isEmpty = function() {
  return this.textContent.trim() === "";
}

SomeElement.isEmpty();

function emptyElementNode(node) {
  return node.textContent.trim() === "";
}

var xo = TicTacToe.getElementsByTagName('div');

for (var i = 0; i < xo.length; ++i) {

	if (emptyElementNode(xo[i])) {
    xo[i].classList.add('highlight');
    xo[i].textContent = "⚬";
  }

}
#TicTacToe {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-gap: 0.063rem;
  width: 6.25rem;
  height: 6.25rem;
  align-items: center;
  justify-items: center;
  margin: -0.063rem;
  overflow: hidden;
}

#TicTacToe {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-gap: 0.063rem;
  width: 6.25rem;
  height: 6.25rem;
  align-items: center;
  justify-items: center;
  margin: -0.063rem;
  overflow: hidden;
}

#TicTacToe div{
  position: relative;
}

#TicTacToe div::before {
  content: "";
  display: block;
  position: absolute;
  width: calc(6.25rem / 3);
  height: calc(6.25rem / 3);
  left: 50%;
  top: 50%;
  transform: translate3d(-50%, -50%, 0);
  background: #fff;
  z-index: -1;
  outline: 1px solid #222;
}

#TicTacToe .highlight::before {
  background: #ddd;
}

#TicTacToe div{
  position: relative;
}

#TicTacToe div::before {
  content: "";
  display: block;
  position: absolute;
  width: calc(6.25rem / 3);
  height: calc(6.25rem / 3);
  left: 50%;
  top: 50%;
  transform: translate3d(-50%, -50%, 0);
  background: #fff;
  z-index: -1;
  outline: 1px solid #222;
}

#TicTacToe .highlight::before {
  background: #ddd;
}
<div id="TicTacToe">
  <div>⚬</div>
  <div>×</div>
  <div>×</div>
  <div>⚬</div>
  <div>⚬</div>
  <div>×</div>
  <div></div>
  <div>×</div>
  <div>⚬</div>
</div>
like image 29
darcher Avatar answered Oct 03 '22 23:10

darcher