getDate() from Javascript returning NULL

Asked

Viewed 74 times

-1

(function(){
    var data = new Date();
    var dia = document.querySelector('.table tbody tr > td');
    dia.textContent = data.getDate();
})();

I have this function in Javascript. It always returns NULL. Why does this happen?

  • What is it that returns null?

  • as said in the answer checks if the "path" of the selector is correct

  • I solved the problem.... I was playing JS on top of HTML. That is: It would always be NULL because it read JS first. Sorry about the noobeira, guys. =

2 answers

1

I simulated your code here and it’s working normal. See if the dial isn’t wrong.

(function(){
    var data = new Date();
    var dia = document.querySelector('.table tbody tr > td');
    dia.textContent = data.getDate();
})();
<table class="table">
  <tbody>
    <tr>
      <td>data vem aqui</td>
    </tr>
  </tbody>
</table>

0

I updated your function to return Date inside an element with ID, but you can use querySelector if applicable:

$(function() {
    var data = new Date();
    var dia = document.querySelector('#aqui');
    var mes = data.getMonth()+1; // Janeiro é 0!
    if(mes < 10) mes = '0'+mes;
    var ano = data.getFullYear();
    dia.innerHTML = data.getDate() + '/' + mes + '/' + ano;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p id="aqui"></p>
  
  
  
</body>

  • Funny that I passed an id in td and still the querySelector returns null.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.