JS Modify InnerHTML

Let’s build on top of the previous post and print things “on the screen” instead of logging them in the browser’s console.

This can be done by modifying the HTML code of the page using something called the innerHTML function in JS.

<button id="myBtn"> Load some data! </button>
<div id="hidden-div"></div>
<script type="text/javascript">
    var myBtn = document.querySelector('#myBtn');
    var myDiv = document.querySelector('#hidden-div');
    myBtn.addEventListener('click', displayData);
 
    function displayData() {
        myDiv.innerHTML = 'Hello';
    }
</script>

The code above is copied from the previous post with two extra lines (2nd and 5th) and one small change on line 9.

Second line adds a division with id hidden-div, 5th line adds a selector for that new division and 9th line modifies the innerHTML of that division by printing Hello inside it (whenever the displayData function is triggered).

The end result – whenever someone hits the button Load some data! it returns Hello on the web page.

Leave a comment