Hello Word javascript

2

I'm following the firefox tutorial but I'm not able to run a hello word. Follow the code.

HTML code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Javascript 01</title>
    <script type="text/javascript" src="scripts/main.js"></script>
</head>
<body>
    <h1>Teste</h1>
</body>
</html>

JavaScript code

alert('123');
var myHeading = document.querySelector('h1');
myHeading.textContent = 'Hello world!';

alert works, it's getting there. I wanted to know why you did not change the text from h1 to Hello Word.

    
asked by anonymous 25.11.2016 / 13:22

2 answers

3

Because your Javascript is in head , that is, it is running before h1 is in DOM .

Option 1 - Load at the end of the body:

Change to the following:

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Javascript 01</title>
  </head>
  <body>
    <h1>Teste</h1>
    <script type="text/javascript" src="scripts/main.js"></script>
  </body>
</html>

Option 2 - Using the onload event:

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Javascript 01</title>
    <script type="text/javascript" src="scripts/main.js"></script>
  </head>
  <body onload="executar()">
    <h1>Teste</h1>
  </body>
</html>

JS

function executar() {
  alert('123');
  var myHeading = document.querySelector('h1');
  myHeading.textContent = 'Hello world!';
}
    
25.11.2016 / 13:26
0

Another option is to put the code in onload :

window.onload = function(){
    var myHeading = document.querySelector('h1');
    myHeading.textContent = 'Hello world!';
}
    
25.11.2016 / 13:26