[Web] I don’t know Basic DOM property

less than 1 minute read

My mistake with EventListener

Today I wrote code doing some Event(addEventListener).

I did write code of addEventListner, but I can not get right result.

This is my first code I wrote

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
        <script>
            var btn = document.getElementById("btn");
            btn.addEventListener("click",btnclick);
            function btnclick(){
                alert("test");
            }
        </script>
</head>
<body>
    <div>
        <button id="btn">click</button>
    </div>
</body>
</html>

I got this error message</br> </br> the reason why is that before DOM is made up, JS code is executed, so JS code can not access element By Id

Solution is that writing the code about accessing elementById after DOM is made up like below

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>
        <button id="btn">click</button>
    </div>
</body>
    <script>
        var btn = document.getElementById("btn");
        btn.addEventListener("click",btnclick);
        function btnclick(){
            alert("test");
        }
    </script>
</html>

and then I got right action. This code makes up DOM first and then act JS code.

Tags:

Categories:

Updated:

Leave a comment