Hello Word javascript

Asked

Viewed 194 times

2

I am following the firefox tutorial but I am 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!';

The alert works, ta getting there. I wondered why you didn’t change the text of h1 for Hello Word.

  • 1

    Welcome to Stackoverflow in English. I edited your question to remove the greetings, as we usually keep them as clean as possible to focus on your scheduling question. If you are interested in visiting a part of the site that is not aimed to ask questions can know the Stack Overflow Chat in Portuguese. If you have questions about the operation, rules and procedures of the site visit the Stack Overflow in English Meta :)

2 answers

3


Because his Javascript is in the head, that is, is being executed before the h1 is in the 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!';
}
  • But, this is the standard html 5 ? There is no other method ?

  • @Abnerpassosmagalhaes in reality you will never alter an element of the DOM right at the start of your script, agree? Otherwise you have to put in the event onload page.

  • thanks!! It worked.

  • truth. Thanks man!

  • @Abnerpassosmagalhaes Was the answer helpful to you? Don’t forget to mark it so it can be used if someone has a similar question!

  • From what you’re saying, it seems to be the case mark an answer as accepted. Here we do not write "solved" in the question. If you have an answer that really helped you, mark it as accepted. If you came to the solution on your own, put in the solution as an answer. So content is more organized and easier to find in the future by other people with similar problems.

Show 1 more comment

0

Another option is to put the code in the onload:

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

Browser other questions tagged

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