Deprecated innerHTML

This is a JavaScript example of how to use the createTextNode instead of the deprecated innerHTML. There is also an example of how to use the removeChild function if the node you want to add to has child nodes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<script type="text/javascript">
 
	function redmatchJobCount() {
 
		var redmatchJobCount = "<?php echo(getRedmatchJobCount()); ?>";
 
		// create this: <span class="count">309</span>
		var textObj1 = document.createTextNode(redmatchJobCount);
		var span1 = document.createElement("span");
		span1.className = "count";
		span1.appendChild(textObj1);
 
		// create this: <span class="jobs_online">Jobs Online</span>
		var textObj2 = document.createTextNode(" Jobs Online");
		var span2 = document.createElement("span");
		span2.className = "jobs_online";
		span2.appendChild(textObj2);
 
		// remove existing child nodes from the parent node
		while(document.getElementById('jobcount').hasChildNodes()) {
			document.getElementById('jobcount').removeChild(document.getElementById('jobcount').firstChild);
		}
 
		// add newly create span tags to the parent node
		document.getElementById('jobcount').appendChild(span1);
		document.getElementById('jobcount').appendChild(span2);
 
	}
 
	if(typeof addLoadEvent != 'function') {
		function addLoadEvent(func) {
			var oldonload = window.onload;
			if (typeof window.onload != 'function') {
				window.onload = func;
			}
			else {
				window.onload = function() {
					if (oldonload) {
						oldonload();
					}
					func();
				}
			}
		}
	}
 
	addLoadEvent(redmatchJobCount);
 
</script>
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply