Javascript: Changing content 'on the fly'!
You may have noticed that using document.write in the head of HTML documents results in a complete wipe of the page – this deems document.write useless in a few places. So how do you get around this? Well luckily it's not all that difficult (so this tutorial isn't going to be a long one).
The first thing we need to do is target the element we want to change the content of. If you know anything about Classes and IDs in HTML, this knowledge will come in useful now as we are going to find the element we want to change the content of via the use of an ID. We can find elements in our document by their ID, via JavaScript and the getElementById method on document. This method simply takes the element's ID – so if the element we wanted to change the content of has an ID of "message_of_the_day", we could target it with the following JavaScript:
document.getElementById('message_of_the_day')
We can then set the HTML inside the thing that has the ID that we targeted by simply setting the element's innerHTML to whatever we want. So if we wanted to change "message_of_the_day"s HTML to "Don't forget to be awesome!", then we could do something like the following:
document.getElementById('message_of_the_day').innerHTML = 'Don\'t forget to be awesome!';
It's as simple as that! This technique could be useful for changing content via an external JS file in the head, or could by used in any JavaScript snippet to change content in a certain area. A good application might be a basic slider where the content is changed when a button or link is pressed, if you want a challenge – try creating something like this now!
Back to Javascript

