0

Whatever I do the console.log returns value 0 tried in the browser(Google Chrome and Firefox) but it works fine there... Javascript is returning the length of elements having id el as 0 there are some elements (118 elements of the periodic table) but it shows 0

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="styles/style4.css">
  <meta charset="UTF-8">
  <meta name="author" content="Rakshit Jain">
  <meta name="description" content="My assignment">
  <meta name="keywords" content="assignment">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Assignment 4</title>
</head>
<script>

   console.log(document.querySelectorAll('#el').length); 

</script>
<body>
  <h1>Assignment 4</h1>
  <table>
    <tr>
      <th colspan="18">The Periodic Table</th>
    </tr>
    <tr>
       <td id="el">H</td>
       <td class="empty" colspan="16"></td>
       <td id="el">He</td>
      </tr>
      <tr>
       <td id="el">Li</td>
       <td id="el">Be</td>
       <td class="empty" colspan="10"></td>
       <td id="el">B</td>
       <td id="el">C</td>
       <td id="el">N</td>
       <td id="el">O</td>
       <td id="el">F</td>
       <td id="el">Ne</td>
      </tr>
  </table>
</body>
</html>
  • You're calling `document.querySelectorAll()` before you've loaded those elements in the DOM. Also, IDs have to be unique. – Barmar May 28 '20 at 11:32

1 Answers1

0

You need to move your script tag just before the closing tag (or execute your code using DOMContentLoaded event handler on window). Otherwise the code will run before your HTML is there, that's why you are getting zero length.

Ján Jakub Naništa
  • 1,880
  • 11
  • 12