The script attribute used in html cannot run as expected [duplicate]

This is an example from w3school, I practice typing html, but I don’t know where is the problem
My intention is for the button to hide the city element, but somehow the button doesn’t work.

<!DOCTYPE html>
<html>
    <head>
        <meta charset = "utf-8">
    </head>
    <body>
        <button onclick = "myFunction()">Hide Elements</button>
        <h2 class = "London">London</h2>
        <p>london is beautiful.</p>

        <h2 class = "Tokyo">Tokyo</h2>
        <p>Tokyo is beautiful.</p>

        <h2 class = "Paris">Paris</h2>
        <p>Paris is beautiful.</p>

        <script>
            function myFunction(){
                var x = document.getElementsByClassName("city");
                for(var i= 0;i < x.length;i++){
                    x[i].style.display = "none";
                }
            }
        </script>
    </body>
</html>