Tuesday, July 16, 2013

Accessing the DOM

JavaScript can be used to get a handle on a particular part of an HTML document. Let's use this simple HTML as an example:

<html>
<head>
<title>
</title>
</head>
<body>
  <h1>My List</h1>
  <ul id="list"><li>Item 1</li><li>Item 2</li><li>Item 1</li></ul>
</body>
</html>

Here I have an unordered list with three list items. With JavaScript, I can use the the method document.getElementById() to grab a hold an element with a unique id. Notice that in the HTML, I gave the <ul> element an id of "list". We use ID's to access an element with CSS and we do it in a very similar way with JavaScript. If I write in my script:

 var list = document.getElementByID('list')

 I stored a variable called list that gives me access into the DOM. From here I can do things like:
  • determine the node type
  • change the inner HTML
  • and determine how many child nodes there are
Another method is to grab a hold of part of the DOM is document.getElementsByTagName(). If I write:

var listItems = document.getElementsById('li') 

This will find me all the nodes with the list item elements and store it as an array. If you wanted to access the second node for example, you would write

listItems[1]


And this will grab the second list item.

No comments:

Post a Comment