var elemento = document.getElementById('parrafo1');
console.log(elemento);
<!DOCTYPE html>
<html>
<head>
<title>Pagina prrona 2</title>
<script type="text/javascript" src="java.js"></script>
<link rel="stylesheet" type="text/css" href="Estilos/styles2.css">
</head>
<body >
<h1 id="parrafo1">Parrafo 1</h1>
</body>
</html>
And when I try to see the value of "element", it says "null", what is happening? Some bad syntax?
What happens is that the js script is loading before the HTML elements of the body and that is why it does not detect the element with the id
parrafo1
.You would have to place the script as follows:
Now if it should detect the element
h1
with the idparrafo1
.The problem is surely that the script is being loaded before the full page is loaded, in order for it to work you must enclose your javascript code inside the load function:
Here your code works as is without putting load I guess because stackoverflow first loads the entire dom and then the script, but in a page opened locally it may not work.
Suggestions to avoid this:
ctrl+f5
(not onlyf5
)clear caché
https://chrome.google.com/webstore/detail/clear-cache/cppjkneekbjaeellbfkmgnhonkkjfpdn?hl=es