Using javascript to dynamically change HTML content

This was written to solve a problem of integrating a client's map data into Wordpress. There were two versions of the map which were switched using PHP. Rather than hack the Wordpress code I thought it more elegant to use a Javascript fuction. I did what all web developers worth their salt do, scavanged around the internet for it!

There were functions out there that looked along the lines of what I required but not quite and usually to restrictive to readily adapt. So, I ended up writing my own...

The code is web compliant and can be adapted to work with other types of form elements or even links. For me, I was able to drop this code into a Wordpress post and pull in flood tide maps that were delivered via iframes from another website and then switch between different tide height maps.

A working example

In this example javascript is used to dynamically change text, in this case links, utilising a drop down box.

The Code

The Javascript can be placed in a separate file, in the head of the HTML page or in the body of the HTML page. The form and switching content paragraph are placed wherever desired in the body.

<script type="text/javascript">
	function switch_content(){
	var choosen_option = document.getElementById("form_choices").option_choices.value;
	if (choosen_option ==10){
		var google = ('<a href="">Google</a>');
		document.getElementById("switched_output").innerHTML = google;
	if (choosen_option ==20){
		var wikipedia = ('<a href="">Wikipedia</a>');
		document.getElementById("switched_output").innerHTML = wikipedia;

<form id="form_choices" action="#" onsubmit="return false;">
		<label for="drop_down_options"> Choose a website:</label>
		<select id="drop_down_options" name="option_choices" onchange="return switch_content()">
			<option value="10" selected="selected">Google</option>
			<option value="20">Wikipedia</option>

<p id="switched_output"></p>


This document is free to use and distribute under the GNU Free Documentation License.

Gary Hollands - July 2013.