📖 Manipulating DOM Nodes with JavaScript
Document Object Model (DOM)
There is an important concept in JavaScript that defines the way information is accessed in the web page. The document object contains all the information related to the display of the web page. All the elements are organized by relationship to each other in a tree-like structure. This is called the Document Object Model (DOM). It is a way of visualizing all the elements of the web page making access to those items more intuitive. There is a good explanation of the DOM at the W3 Schools.
- Elements nested inside of another element are children of that element.
- All children of an element are siblings.
- Elements that contain another element are the parent of that element.
Code | Explanation |
---|---|
|
For the example code on the left, here are some of the relationships:
|
Accessing the DOM Nodes
The DOM allows JavaScript to communicate with elements on a web page, the browser window, etc. It includes all html elements, attributes and relationships on a web page as well as the text. Each individual element, tag or text is called a node. The DOM is represented as a tree-like structure with branches. More specifically, the DOM elements are referred to using common family tree descriptors. For example, nested elements are called child elements and so on. JavaScript provides many built-in methods for accessing nodes.
Select a Node from the DOM Using JavaScript
- Select all elements of the same type on a page
document.getElementsByTagName('elementName');
- Select a specific element on a page with an id
document.getElementById('idName');
- Select all elements of the same class attribute value on a page
document.getElementsByClassName('elementClass');
- Select one element using a css style selector on a page
document.querySelector('[.|#]selectorName');
- Select all elements of the same css style selector on a page
document.querySelectorAll('[.|#]selectorName');
JavaScript also provides a means of accessing and changing values.
- Getting an attribute value
document.getAttribute('attributeName');
- Setting an attribute value
document.setAttribute('attributeName', 'attributeValue');
- Getting the HTML value of an element
document.getElementById('idName').innerHTML;
- Setting the HTML value of an element
document.getElementById('idName').innerHTML = "New HTML";
This is only a sample of the JavaScript methods for accessing DOM nodes. I think the preferred way of finding DOM elements is to use the querySelector[All](), though all of these work. For a more complete list visit W3 Schools HTML DOM Document Object page.
Manipulating the Page Content
There are some really good tools built-in to FireFox and Chrome browsers to help work with JavaScript. One of the first ones to learn is the console tool. Access your Developer Tools (F12) as usual. Select the Console tab near the Inspector (in FireFox) or Elements (in Chrome). This will allow you to monitor for JavaScript errors and insert JavaScript code into the page.
Dallas College
The heading above uses an id="dallas_college" to identify the text in the heading. This should default to "Dallas College". We are going to change this to "Hello World!" using the code below.
Example
/* Paste the following into the browser console to view the effects. */
/* To retrieve text from an element, select the innerHTML for the element. */
/* This should return the current banner text "Dallas College". */
document.getElementById('dallas_college').innerHTML;
/* To replace text in an element, assign new text to innerHTML for the element. */
/* This should replace the banner text with "Hello World!" */
document.getElementById('dallas_college').innerHTML = "Hello World!";
Let's say we wanted to change a defalut picture on a page to some other dynamically loaded image. We would access the original image from the DOM using the getAttribute then substitute the new image using the setAttribute method. Using the browser console, we access the image src for the current profile picture, then replace it with a new avatar.png image from the userpics folder (located on the server).
Example
/* Paste the following into the browser console to view the effects on the author's image on this page. */
/* Select the original image and assign it to a variable named oldImage. */
var oldImage = document.getElementById('profilePic');
/* Replace the old image with a new image by changing the image src attribute dynamically. */
oldImage.setAttribute('src', '/userpics/avatar.png');
JavaScript Events
JavaScript provides user interactions by responding to events. Anytime something happens on the page an event is triggered. We can tell JavaScript to respond to specific events or listen for possible events. When the event is triggered, JavaScript will carry out the instructions provided in the code. A good example of this is when JavaScript changes the page contents based on a user clicking a button. Here are some examples of coding JavaScript to respond to events.
HTML onClick Attribute
/* The following replaces the default stylesheet with an alternative stylesheet. */ /* Default stylesheet. */
<link rel="stylesheet" href="css/color-scheme1.css" id="color">
/* Add a click event to a button. */
<button onClick="changeStyle('css/color-scheme2.css');">Apply Style</button>
/* Add a function to run on the button click. */ function changeStyle(newStyle){ document.getElementById('color').setAttribute('href', newStyle); } /* The address of the new stylesheet 'css/color-scheme2.css' will be passed to the function when the button is clicked. The function will replace the original file/path with the new one. */
Sometimes you might wish to only change a single CSS property. In that event, you would use the style.property method shown below. This should change the color of the Demo Header to blue with a yellow background.
Demo Header
/* Copy and paste the code below into the console to see the change. */
document.getElementById('demo').style.color = 'blue';
document.getElementById('demo').style.backgroundColor = 'yellow';
/* The color of the Demo Header above should change to blue and it's background-color should be yellow.
Notice the CSS property background-color becomes backgroundColor for JavaScript. */
Links vs Buttons
If you are using links (anchor tags) instead of buttons, you'll need to tell the browser to ignore the link when it's clicked. Many times this isn't necessary as you will want the link to work for users that have JavaScript turned off, but in case you do, here's how to do it.
/* Add a return=false to your function. */
function changeStyle(newStyle){
document.getElementById('color').setAttribute('href', newStyle);
return false;
}
Responsive Navbar Example
Let's pull this all together by demonstrating a real world example of how JavaScript can provide an interesting behavior that is also a great idea for incorporating nav menus on mobile screens and full size menus on large screens. W3 Schools has a good example on how to build a responsive nav bar.