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.

JS Basics – querySelector And addEventListener

Today I’ll cover two basic concepts in JS – QuerySelector and AddEventListener. This is probably something that you’ll use most of the time (if you’re coding in JS or reading a JS code).

Ok let’s start with a simple HTML button having the id myBtn

<button id="myBtn"> Load some data! </button>

Next let’s add the following script under it –

<script type="text/javascript">
 	var myBtn = document.querySelector('#myBtn');
 	myBtn.addEventListener('click', displayData);

 	function displayData() {
		console.log('Hello');
 	}
</script>

This code selects the HTML element and stores it in the variable myBtn. It adds an Event Listener which listens for click and runs the displayData function once triggered.

The function displayData logs Hello in the browser’s console (which can be accessed by OPT+CMD+J).

That’s the basics of JS. In the next post, we’ll have a look at the setTimeout function where we’ll do something exciting and interesting 🙂