Call an API with plain Javascript (youtube tutorial)

This is the source code developed for a Youtube tutorial. We’re calling the Hackernews API and displaying the results in a list. We’re not using any frameworks, so just plain (vanilla javascript).

<html>
    <head>
        <title>Call API</title>
        <script>
            function callApi() {
                document.getElementById("results").innerHTML = "Loading ...";
                fetch("https://hn.algolia.com/api/v1/search")
                    .then(response => response.json())
                    .then(response => {
                            let list = document.createElement("ul");
                            response.hits.forEach(element => {
                                if (element.title) {
                                    let item = document.createElement("li");
                                    item.appendChild(document.createTextNode(element.title));
                                    list.appendChild(item);    
                                }
                            });
                            document.getElementById("results").replaceWith(list);
                        }
                    );
            }
        </script>
    </head>
    <body>
        <button onclick="callApi()">Call API</button>
        <div id="results">results</div>
    </body>
</html>

Leave a comment

Your email address will not be published. Required fields are marked *