JavaScript: Basic DOM manipulation

JavaScript as a language has a couple of built-in objects ready to use such as Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. Depending on your executing environment you may, however, have more objects pre-defined to work with. Most people use JavaScript on their web sites which means the running environment is a browser and it comes with several useful objects. One of these objects is called document and it is the object that we’ll be looking at in this article.

The document object represents the entire HTML structure of the current page and allows for you to easily search the HTML structure using methods such as getElementById and getElementsByClassName. The name of the methods are quite self explanatory and we’ll be using the getElementById method to manipulate a button. We’ll change its text, its background and the font-weight of it:

 

<!DOCUMENT html>
<html>
	<head>
		<title>Javascript DOM manipulation Example</title>
		<script type="text/javascript">
			function handleClick()
			{
				var button = document.getElementById("MyButton");	
				button.innerHTML = "This value just changed!";		
				button.style.background = "#FFF";					
				button.style.fontWeight = "bold"; 					
			}
		</script>
	</head>
	<body>
		<h1>Javascript Button test!</h1>
		<button id="MyButton" onclick="handleClick()">Click here!</button>
	</body>
</html>

What we do here is that we create a function called HandleClick which we hook up to the onclick event of the button. When the button is clicked the function is executed and in it we fetch the button by using the getElementById method of the document object.
The method will return a reference to the button object which is now open for manipulation. We change the text of the button by utilizing the innerHTML property of the button-object. We can manipulate the CSS of the element by going through the style property of the button which contains all the CSS elements ready to be read or written to. Note, however, that some CSS element are hyphenated and they are changed to camelCasing (i.e. font-weight becomes fontWeight and padding-left becomes paddingLeft).

Click here for an example!