Why does Javascript not find a page tag?

1

I have a simple question:

Why does not my alert display the value of the name attribute of the button? Strangely if I insert the javascript code after the <button> tag the alert works normally. Here is the code that does not work:

<html>
    <head>
        <title></title>
    </head>

    <script type="text/javascript">
        var x = document.getElementById('a').name;
        function aoba() {
            alert(x);
        };
    </script>
    <body>
        <button id="a" value="b" onClick="aoba()" name="botão"> BOTÃO 1 </button>
    </body>
</html>
    
asked by anonymous 29.06.2016 / 23:22

3 answers

1

You can use the following code that I think will work

<body onload="aoba()">

You can be sure that it will work, because you are trying to load the variable before the DOM is created, then in case it does not exist yet, but with that code fragment you will cause it, as soon as the DOM is created load the script.

abrsss

    
30.06.2016 / 15:18
3

JavaScript accesses HTML through the DOM, which is a representation of HTML in JavaScript. What happens is that the DOM is not yet ready / interpreted when you run your code. By the time the head tag is read document is not yet accessible to JavaScript.

So you have to put your code after the Browser read the HTML you want. You can do this by placing the JavaScript at the bottom of the page, before closing the body tag, or putting that script inside a function that is called after the page loads (and in this case may be within head as it is now):

window.onload = function(){
    var x = document.getElementById('a').name;
    function aoba(){
        alert(x);
    };
}

This function that runs when the DOM is loaded can be more complex if needed. But for example window.onload serves well.

__

Note, I noticed now that your script tag is not within body nor head . It has to be inside one of them.

    
29.06.2016 / 23:33
1

What happens in your code is that you are capturing the name of your button before it is created on the tree DOM . To resolve this, your Tag script should be below the button.

<button id="a" value="b" onClick="aoba()" name="botão"> BOTÃO 1 </button>
<script type="text/javascript">
  var x = document.getElementById('a').name;

 function aoba(){alert(x);}; 

</script>

You can also capture name within the method to call, this solves the problem

function aoba(){
    var x = document.getElementById('a').name;
    alert(x);
}

And by event onload of your window.

<script type="text/javascript">
    var x;

    function aoba(){alert(x);};

    window.onload = function(){ // acrescenta o name em x quando a pagina terminar se ser carregada.
        x = document.getElementById('a').name;
    }

</script>
    
29.06.2016 / 23:37