New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Start learning with our library of video tutorials taught by experts. Get started

JavaScript Essential Training
Illustration by

Accessing DOM elements


From:

JavaScript Essential Training

with Simon Allardice

Video: Accessing DOM elements

So how do we write JavaScript to grab hold of one of these nodes? And well, it really depends. The main question you have to ask is, is it unique? The thing that you're after, is it unique in the document, and that means does it have an ID? If I'm after, say, an unordered list, I need to ask the question, does it have an ID in the HTML? You know that you can add the ID and class attributes to any of your HTML elements, but that a class can be added to multiple elements, but an ID should only be applied to one. It should be unique.
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
      43s
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye
      58s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
JavaScript Essential Training
5h 31m Beginner Jul 22, 2011

Viewers: in countries Watching now:

Use JavaScript to add new features and a richer, more compelling user interface on web pages. This course keeps current best practices and practical uses for JavaScript in mind, while covering syntax, working with the DOM, and developing and debugging across multiple platforms, devices, and browsers. Author Simon Allardice also shows how to progressively enhance and gracefully degrade web pages, and take advantage of the world of JavaScript libraries now available.

Topics include:
  • Understanding the structure of JavaScript code
  • Creating variables, functions, and loops
  • Writing conditional code
  • Sending messages to the console
  • Working with different variable types and objects
  • Creating and changing DOM objects
  • Event handling
  • Working with timers
  • Debugging JavaScript
  • Building smarter forms
  • Working with CSS, HTML5, and JavaScript
  • Using regular expressions
Subjects:
Developer Web Web Design Programming Languages Web Development
Software:
JavaScript
Author:
Simon Allardice

Accessing DOM elements

So how do we write JavaScript to grab hold of one of these nodes? And well, it really depends. The main question you have to ask is, is it unique? The thing that you're after, is it unique in the document, and that means does it have an ID? If I'm after, say, an unordered list, I need to ask the question, does it have an ID in the HTML? You know that you can add the ID and class attributes to any of your HTML elements, but that a class can be added to multiple elements, but an ID should only be applied to one. It should be unique.

And if the element that you're after has that unique ID, you can grab it in JavaScript by using possibly the most important method of the document object, which is this one, document.getElementById, and you pass in the ID of that HTML element. Now notice the uppercase and lowercase mixture here. It is, of course, case sensitive. So document is lowercase, then a dot, then getElementById. get is lowercased. Every subsequent word begins with uppercase.

Element, By, and Id, but Id is not uppercase D, which often messes people up there. So what does this do? Well, we're going to call it, but not just like this. What we're going to do is create a variable and set it to the result of calling that. So if I want to grab hold of this unordered list that has an id of abc, I'm going to create a new variable called myElement and set it equal to document.getElementByID and pass in abc, the ID of the element.

And what we're doing here is we're creating a variable that is really a handle to that place in the DOM. We can then use that variable, in this case I've called it myElement, to read properties of the element. You can call methods of the element. You can even change that element. Now it's important to understand that when I do this getElementById, I'm not just making this detached copy of this single piece. Now I have a handle right into this document. I can use it to go down to the child nodes.

I can use it to go up to the parent node. It's not the detached copy of the one element; it's more like a pathway into this particular place in the DOM. Well, what if I don't have an ID on the element that I'm after, or what if I want more than one element? Well, then we have the getElementById's close relative, document.getElementsByTagName. Now notice, not getElement, but getElements, plural. What this is going to do is go through our document and give us back any of the element nodes that are anchor elements, a tags in your HTML.

Well, how does that work? So let's say we go back to the same ID of the simplified DOM here. I'm going to create a new variable called myListItems and set it equal to document.getElementsByTagName, passing in li, which means, find me all the nodes that are list item elements and return those. Well, how does it store that in one variable? It makes an array. So it makes an array called myListItems, it finds all the list items in the entire document, and then in each position of the array, in this case, there's three positions to it, we'll have a handle to that particular place in the DOM.

So we could just use the square qrackets and say myListItems(0) or myListItems(1) or myListItems(2). Now if you call the same method, getElementsByTagName and pass in a tag name that doesn't exist, so in my simplified model here I don't actually have any a href elements, what will happen is it will still return array, but the array will be empty. It won't even have a length of 1. It will have a length of 0. There's nothing there. So in this folder that I'm looking at here, I have a web page and some attached CSS and image just to give us something a bit more interesting to look at and to have a bit of content to work with.

If I were to look at the page source of this, there's nothing particularly remarkable. It's standard HTML, although down towards the bottom, I do have a link to a file called script.js just before the closing body tag. And right now there is nothing in script.js. I'm going to open that up in Aptana, though I could open up in any editor. And just to have something else to look at, I'm going to flip over and just open up this HTML file in the same editor.

I'm not intending to change the HTML here; I just want to be able to flip back and forth to it. So I can see by scanning my HTML that I actually have quite a lot of elements that have an ID to them. And the main reason this has been done is so they can be styled with CSS, but it is very handy for us as JavaScript programmers as well. I can see, for example, I have an anchor tag here with an ID of mainTitle.

I'm going to write some code to grab hold of that. So let's create a new variable. I'll call it mainTitle. Again, we must take care to make sure that the casing that we're using to grab it is exactly the same as it is in the HTML itself. The variable I didn't have to call the same name. I can call that whatever I want. And the question is, now what? Well, I have this variable which represents the object, the element object, and like all objects, like dates, like arrays, like even strings, we have things that we can ask for them.

So I'm going to write out a few console messages. And with console.log we can put a string, then a comma, and then some interesting information. So I'm going to say the message "This is an element of type" and I'm typing in my variable name, .nodeType. If you have an editor that pops up some of the auto-completion stuff, then great; otherwise, just type it in anyway.

nodeType will be a property we can access as soon as I have something back from getElementById. If you recall, I said there were three kinds of nodes we were interested in: elements, attributes, and text. Internally, they should have the nodeTypes 1, 2, and 3, so this should write us back out 1. I'll do another one here, console.log. Writing out another property called innerHTML, and as always, paying attention to the case sensitivity of this.

And the last message I'm going to write out is a message that will tell me how many child nodes I have, because when we grab hold of this element, we don't just have the element by itself; we'll also be bringing along references to any child nodes it has, or if I want to look up the way, any parent nodes as well. So every node has a childNodes property that might be empty, but I don't think it is here. It's actually an array, so it itself will have a length property. I'm just going to hit Command+S or Ctrl+S to save this, flip back over into Firefox where I actually do still have this running, and refresh the page.

Now I'm doing console messages, so I need to have Firebug opened to actually see the console. Refresh that page, and we get "This is an element of type: 1." The Inner HTML is apparently Welcome to Explore California! and this particular node has one child node. So we're programmatically reaching into the HTML here, grabbing this content, and finding information about it.

This is the innerHTML path that I was actually pulling out. I'm going to jump back in and do a little bit more code here. Now, let's use the document.getElementsByTagName. What I'm going to do here is create a new variable on Line 7 called myLinks, this will be an array, and tell this to fill it with as many anchor tags as I have. Then I'm going to write out a log message that just says myLinks.length. I'm just going to save that; for me Command+S or Ctrl+S, depending on what platform you're on. Back over into Firefox, refresh the page, and then apparently we have 19 links, 19 anchor tags on this page, and we're getting all those elements by tag name.

Yes, I'm not doing much with them yet, but you can see how we can start to drill down into the properties and the information about that data. So documents.getElementById and getElementsByTagName. Very, very powerful, hugely useful, probably one of the most often used things in all of JavaScript. And they're actually a little bit more powerful than this because even though most people think of this method as document.getElementById, it's more flexible than that.

As soon as I have, say, an element node, I can use the same method at any level in the DOM, not just the top-level document. What does that mean? Let's say, for example, I have a slightly more complex DOM here and I run a line of code here that says getElementsByTagName. So it's document.getElementsByTagName("li"). Give me all the list items back. If I can just run this, what I'll do is I'll grab all the list items from every level of the document.

But let's say that's not what I was after. What I can do is kind of a two-stage thing here. First, I would use document.getElementById to grab that unordered list with an ID of abc, and that gives me a new variable called myFirstList. Then I'm going to call getElementsByTagName again, but instead of using the document to call it, I'm going to say myFirstList.getElementsByTagName. And what that means is it'll start at the unordered list position and look downwards and only give me back those list items.

So I'm using another element, and you'll find this all the way up and down the DOM, that you're able to reuse the same method. Once you start to get to grips with the properties that are available and the methods that are available, you can pretty much get anywhere you want.

There are currently no FAQs about JavaScript Essential Training.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.