navigate site menu

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

JavaScript: Enhancing the DOM

JavaScript: Enhancing the DOM

with Ray Villalobos

 


The Document Object Model (DOM) is at the core of every HTML page. In order to develop dynamic HTML pages, a front-end developer needs to understand how JavaScript connects to and controls the DOM, allowing you to create, modify, delete, and edit existing page content. This course focuses on helping you understand the DOM elements, and shows the different ways JavaScript gives you access to them and makes it easier to work with the DOM. Author Ray Villalobos covers navigating the DOM, selecting elements, modifying HTML attributes, editing nodes, and much more.
Topics include:
  • What is the DOM?
  • Choosing and isolating elements
  • Traversing up and down DOM nodes
  • Changing HTML attributes
  • Modifying elements as text
  • Creating and appending nodes
  • Cloning and removing nodes
  • Adding a bubbling event listener
  • Adding and resizing images
  • Handling clicks

show more

author
Ray Villalobos
subject
Developer, Web, Web Design, Web Development
software
HTML , JavaScript
level
Intermediate
duration
2h 3m
released
Jun 10, 2013

Share this course

Ready to join? get started


Keep up with news, tips, and latest courses.

submit Course details submit clicked more info

Please wait...

Search the closed captioning text for this course by entering the keyword you’d like to search, or browse the closed captioning text by selecting the chapter name below and choosing the video title you’d like to review.



Introduction
Welcome
00:00 (music playing)
00:04 Hello there. My name is Ray Villalobos and welcome JavaScript Enhancing the DOM.
00:07 In this course, I'm going to show you the document object model is tightly
00:11 integrated into JavaScript. I'll start by showing how the developer
00:15 tools work by chrome and how to grasp commands by the JavaScript counsel.
00:20 Then you'll learn to select notes by ID, class name and with the new query selector.
00:25 I'll show you how to modify regular, restricted and HTML5 data attributes in
00:29 dom element. Next, we'll learn to create, append,
00:34 clone, replace and remove existing nodes. Finally, we'll build a project that
00:39 utilizes what you've learned by building a moto popup.
00:43 We'll create an overlay with a centered image, style it via JavaScript, and
00:46 handle events like clicks, scrolling and resizing the document window.
00:51 If you're looking to master how you can control elements in your document through JavaScript.
00:55 And this is the course for you, so let's get started.
00:58
Collapse this transcript
What you should know before watching this course
00:00 Before you watch this course, I want to talk about some things you need to be
00:03 familiar with before taking the course. You should be familiar with building
00:07 online projects and know how HTML works. A really good course to check out is HTML
00:12 Essential Training with Bill Weinman. You should also be familiar with basic
00:16 JavaScript concepts. If you need help, check out Simon
00:19 Allardice's JavaScript Essential Training.
00:22 We'll be working with a text editor in this video.
00:25 So, you should be comfortable editing with tex editors like BB Edit, Sublime
00:28 Text or others. In this course, I'm going to use an
00:31 editor called Sublime Text. You should use your favorite text editor.
00:35 If you want to learn more about Sublime text, check out this course and Up and
00:39 Running with Sublime Text. It doesn't really matter which text
00:42 editor you use as long as there's something you're with.
00:44 With just a little bit of background experience, you should have no problem
00:48 taking this course.
00:50
Collapse this transcript
Using the exercise files
00:00 If you are a premium member of the lynda.com online training library, you
00:03 have access to the exercise files used throughout this title.
00:07 Inside the Exercise Files folder, you'll find folders for each video in this series.
00:12 Inside those folders, you'll see a copy of a folder called the dom.
00:16 We usually have one of the files in this folder open in our text editor and/or our browser.
00:22 Once you get to the project part of this course, you'll see that there is a
00:25 Working folder and a Finished folder. The Working folder has a copy of the
00:29 website when we began the video, and the Finished folder has a copy of it at the end.
00:35 If you're a monthly member or annual member of lynda.com, you don't have
00:38 access to the Exercise Files. But you can follow along from scratch
00:42 with your own assets. So let's get ready to explore it down
00:46 with JavaScript.
00:47
Collapse this transcript
1. Getting Started
What is the Document Object Model (DOM)?
00:00 Before we get started we need to talk about: what the DOM is, why its
00:03 important, and discuss some DOM related terminology.
00:06 The DOM is and acronym for Document Object Model.
00:10 Its job is to describe the structure of a HTML document and the relationship
00:14 between different elements like tags, attributes, and texts on a page.
00:18 As you add, delete or modify existing elements on your website, you're creating
00:23 structure that a browser interprets as the DOM.
00:26 So, if I go to this page and I add a new navigational element.
00:31 (SOUND). Then I'm adding an additional node to
00:35 this page's DOM. This node has different relationships,
00:38 like siblings and parents. So, the other li elements on this list
00:42 are the siblings of the new node I just created.
00:45 The ol tag is it's parent. The DOM is also the API that gives
00:49 languages like JavaScript and CSS a way to define and modify the existing document.
00:55 So, I have an article tag here with an id of main as well a headline right underneath.
01:01 If I go to the CSS with this document I can access that element each 1 node and
01:05 ask the browser to change it's color. The browser knows how to access this
01:10 element, because it looks at the HTML I wrote, and creates a DOM tree.
01:14 Once that structure exists, it can can map the CSS I wrote and target a specific
01:20 element in the page. It's really best to think of the DOM as
01:23 an upside down family tree. I'm working with a really simple webpage
01:27 with a traditional HTML structure plus a header, an article tag, and a footer.
01:31 At the top of the family tree is the document itself.
01:35 And then what we called a root element, which is normally the HTML tag.
01:39 Inside that element, we have children of the html element, which is normally the
01:43 head and the body tags. Inside those, we may have some additional elements.
01:48 For example, in the head section, we may have a title element, a script tag, and
01:53 maybe a call to an external style sheet. Inside the body tag we may have a header,
01:58 and that header can have a nav, and that nav can have a list of links.
02:04 Each one of those links may have an anchor tag inside them.
02:07 We could also have an article tag, with a series of headlines and paragraphs.
02:18 Every element in the DOM, including the text and attributes are considered nodes.
02:23 Nodes can be both parent, and have children elements.
02:26 But they can also have other relationships.
02:29 Elements in the same level is known as siblings.
02:32 So these h1 and paragraph tags are considered siblings.
02:35 So are these li tags. Siblings are elements with the same parents.
02:39 The first and last children of an element have special names called first child and
02:43 last child. The rest of the children of the element
02:46 are known as child nodes. Remember that browsers use your HTML code
02:50 to create this DOM structure. And this is why it's really important to
02:53 write clean and valid HTML. So that your CSS and JavaScript code can
02:57 access and modify existing elements without any problem.
03:01
Collapse this transcript
Navigating the DOM with developer tools
00:00 If you've been a web developer for any length of time, you've probably peeked at
00:04 the source code for websites. It's usually under an option in the
00:07 developer tools in your browser called View Source.
00:11 The problem with View Source is it only shows you only the original HTML for the
00:14 page, when it is loaded, as you add and delete elements to use interactions on a page.
00:20 The DOM grows and shrinks dynamically. That's why most browsers have another
00:24 option called the Developer Tools. In this movie, we're going to take a look
00:28 at some of the tools for managing the DOM in Google Chrome.
00:30 There's a few ways to get to these tools. The most obvious is going through the
00:35 menus and choosing Developer Tools from the View menu.
00:38 You may want to remember the keyword shortcut for your machine.
00:41 I'm using a Mac, so mine is Cmd+Option+I. If you're using a PC, this would be Ctrl+Alt+I.
00:49 When you first pull up the tools, notice that there's different tabs at the very top.
00:53 There's tabs like Elements, Resources, Network, et cetera.
00:57 You can navigate through the different tabs, holding down the Cmd key on a Mac,
01:00 or Ctrl on a PC, and using the bracket keys.
01:03 The right bracket navigates through the tabs to the right, and the left bracket
01:07 takes you to the left. When working with the DOM, we're really
01:10 interested in two tabs. The Element tab, as well as the Console,
01:14 which is the last tab. You can go to the console directly with Cmd+Option+J.
01:20 That turns it on and off. So even if I'm in the Elements tab, I hit
01:24 Cmd+Option+J, it takes me directly to the console.
01:27 That would be Ctrl+Alt+J on a PC. By default, your dev tools are on the
01:33 bottom of the screen. You can also undock them by hitting this
01:36 button at the bottom of the screen. Now, this becomes a separate window.
01:42 If I click on this button again, then they'll dock again into the bottom of the
01:45 current document. If you've got a white screen you can also
01:48 place the tools to the right. You have to click and hold this button
01:52 down and select this little option. Now the tools will appear on the right
01:56 hand side of your screen. And that's good if you've got a really
01:58 wide screen. Now, when you toggle them, by hitting
02:02 this toggle right here, it'll go from the bottom view to the side view.
02:06 If you want to switch back to extracting the dock as a separate window, you can
02:11 click and hold down the mouse and select this option right here.
02:14 This'll open it up in a new window. And clicking will take you back to the
02:18 other view. So I'm going to keep my dock at the
02:20 bottom of the screen, so I'll choose this option.
02:24 The Elements tab and the Console are super far apart, but if you click on this
02:28 icon at the bottom of the screen, you can temporarily show the console in any view.
02:32 So I'm going to switch back to the Elements tab, and I'm going to make this
02:35 window bigger. I can go to the edge and just click and
02:38 drag this up, and then I'm going to hit this button right here.
02:40 And it automatically pulls a version of the console right underneath the Elements tab.
02:47 You can also do this by hitting the Esc key and it toggles that on and off.
02:52 The Elements tab shows you a visual representation of the DOM on the left and
02:57 on the right, you can modify the styles of the document.
02:59 Since we're working on JavaScript in the DOM, we're really interested on this left
03:03 side of the window. Notice that you can navigate through the
03:06 DOM by clicking on these little triangles to expand the DOM tree.
03:11 So I can open up this header element. And open up this Nav right here.
03:14 Open up the ordered list. And then click on one of these list items.
03:18 You can also use the arrow keys and sometimes that's a little faster.
03:22 So if you hit up and down you navigate up and down the DOM.
03:25 If you hit the right arrow, then you'll expand a DOM element.
03:30 And if you hit the left arrow, you'll collapse it.
03:33 When you highlight an item in the elements tab, it gets highlighted in the
03:37 main document window, so you can see that, if I choose this article, the
03:41 article area in my document area becomes blue.
03:45 There's also a little option that pops up.
03:46 But right now, says article pound main and is showing you the dimensions of that
03:50 element in the current window. Notice that at the bottom it also gives
03:55 you breadcrumbs right here and if I go deep into some of these element we can
03:59 see that this grows. And you can can click on these tabs to
04:03 navigate to that DOM element. You can also turn on the document
04:07 inspector at the bottom of the screen. That's this little icon right here.
04:10 If I turn that off, you'll notice that I can just navigate to my document as normal.
04:14 If I roll over in the navigation these things highlight.
04:17 If I turn this on, now when I go over the document the elements highlight on screen.
04:22 So if I click on this element it'll highlight on the DOM.
04:26 It's sort of the reverse of navigating down here.
04:29 Now, once you click you're back in normal mode and notice that if I try to select
04:34 something here, it doesn't happen any longer.
04:35 So I would have to click on this icon again to get to that mode again...
04:40 Sometimes it's useful to see your document and pretend a user is rolling
04:44 over an area. So you can do that by clicking on the
04:46 elements, so let's click on artists right here.
04:49 And then over here on the right hand side you can click on this toggle element
04:53 state icon. And then, you can have it pretend that
04:56 somebody's rolling over or hovering over that particular element.
05:00 Notice that it's showing the different background, that happens if somebody
05:03 rolls over an element. That's now looked into position.
05:07 You can temporarily edit the source of a document by selecting a line and then
05:11 hitting Enter or Return. So if I click on this and I hit Enter
05:15 (SOUND) notice that it lets me edit the href.
05:17 If I hit the Tab key it's going to let me edit next to the href.
05:21 Let's go ahead and click on this item right here and hit Enter.
05:25 And notice that I can modify the class. And if I hit Tab again, it lets me add
05:29 something else in here. So I can maybe have an ID.
05:34 And now that's been added into the DOM. Now these changes are temporary and will
05:39 be lost whenever you reload the page. i am going to hit Cmd+R and reload the
05:43 page, and notice that all my changes are gone including the hover command.
05:47 Now, so let me do that again. I will go over here into the home item
05:52 this time and select hover. Notice that there's also little marker on
05:56 the left hand side that's showing you that this element is in hover state.
06:01 So as I mentioned you can double-click on an element or hit Return to edit a
06:04 specific element. You can Tab through the different items
06:07 in that element. But this sometimes is kind of a little
06:10 bit of a weird way of editing. So you can go into regular HTML editing
06:14 mode by hitting the F2 key on your keyboard.
06:17 You may have to press the Function key, depending on what you're using.
06:20 So if I do that, you can see that I can edit this in normal html mode like I
06:25 would on a text editor. This option is also available by
06:28 right-clicking on a line. So if I click on this, and I right-click,
06:32 which is Ctrl+click on a one-button mouse.
06:35 Then you can select Edit as HTML. Now, there is a lot of additional goodies
06:40 you can access by right-clicking on things.
06:43 So let's take a look at some of those. If you right-click on any element on the
06:47 page and select Inspect Element, it takes you directly to that element in the DOM.
06:54 You can also force a state from this pop up windows.
06:57 So, if I right-click on top of the A tag here, I can select Force Element State > :hover.
07:02 It's like I can from this window over here.
07:04 Now, you can also do Copy XPath and that gives you a copy of the path to this element.
07:11 So, if I just paste that right here, you can see that it's sort of like the breadcrumbs.
07:15 It tells you how to get to that specific element.
07:17 (SOUND) One more thing that you can do is hit the Cmd+F button or Ctrl+F on a PC,
07:24 and choose to find an element just by typing it in.
07:27 So if I want to get to the main ID here I can just type main right here and it
07:31 takes me directly to that. That's really useful on a very, very long
07:35 document where you're not really sure where something is.
07:38 And you can go through each element by doing this, going up and down if there's
07:42 more than one. Let's try to look for list item elements here.
07:45 So it's finding that element, and then noticing that there are six of them.
07:49 And I can navigate through them like this, or hit Cmd+Shift+G or Cmd+G to go
07:54 up and down those elements. It's always a good idea to spend some
07:58 time with your tools and learning how to use the developer console is really useful.
08:03 If you invest a little bit of time on memorizing some of these short cuts
08:06 you're going to save yourself a lot of time when you're developing.
08:09
Collapse this transcript
Testing JavaScript commands with the console
00:00 In the last movie, we learned how to work with the developer tools.
00:03 And how to activate the console. In this movie, we're going to focus just
00:06 on the console. So the quickest way to get to the console
00:10 is by hitting Command+Option+J. And I'm using a Mac right now.
00:14 On a PC, Command is usually Ctrl, Option is usually Alt.
00:17 So this would be Ctrl+Alt+J. It might be more convenient, though, to
00:22 call the console within the elements panel.
00:24 So, you can do that by clicking on the Elements panel and then hitting the Esc key.
00:28 That toggles the console on and off. The DOM can be accessed by using selectors.
00:34 So if I just type in document, it selects the entire DOM and I can click on it,
00:37 just like I can with the Elements tab. The DOM has added completion, so as soon
00:44 as I start typing doc, it's suggesting that I probably want the document, so I
00:48 can hit Tab and then Return to execute that command.
00:54 If you type in a period after document, then it's going to select from this list
00:57 of options, all the methods and properties available to this element.
01:02 So if I start typing b for the body, it shows me a shorter list, and I can use
01:05 the arrow keys to move up and down this or just click on it with the mouse.
01:11 (SOUND) So document body takes you directly to the body element, of course
01:15 document head takes you directly to the head.
01:19 Now I can hit the Return key here to get to the end and then return again to
01:22 execute that command. Once you're in, in node of a DOM tree,
01:26 you can get to any of the subnotes using some of the normal JavaScript methods.
01:31 So let's get the child notes of the body element.
01:36 Body, and then type in child nodes, and remember Nodes is capital here.
01:42 Now this shows the list of all the nodes in the body in an array notation.
01:48 I can also hit the up and down arrows to cycle through the list of current commands.
01:54 You can also do that by hitting Ctrl+P or Ctrl+N.
01:56 When you see an array notation like this it means you can access an element by
02:00 typing in the array notation. So if I use brackets here and then select
02:04 element 1, it's going to return the header.
02:07 I'm going to hit up a few times so as to get this all entire list of nodes.
02:13 And notice that you can still click on these triangles to expand some of these elements.
02:18 Now sometimes it's a little more useful to see this as a vertical directory lists.
02:23 So you can type in something like dir(document.body, childNodes) and hit Return.
02:32 And now it's a vertical list. You can of course use the normal
02:37 JavaScript commands to access nodes as well, so we can do something like document.getElementByID.
02:47 Then, I'm going to type in ('main') and that gives me the element with an ID of main.
02:53 Of course, you can also use the JavaScript querySelector method which is
02:55 quite nice. Get to a document.
02:59 And I hit the up arrow here and I'll do querySelector, and then type in what I
03:05 would normally type in, in a CSS rule. So you can say pound main and that takes
03:12 you to the same place. Now the console provides a shortcut for
03:17 this querySelector method. You can get to it by hitting the dollar
03:21 sign and then, in parentheses, just type in anything that you would type in as a
03:24 selector for CSS. And say pound main (SOUND) and that takes
03:29 us to same element. You can try other things like just the tag.
03:32 So I'll get to the footer tag like this, and maybe something more complicated.
03:38 We'll try header and then find the navigation inside and ordered list
03:42 element and then I'm going to use the greater than sign and then a list item
03:46 element in there. So if hit Return, it gets the first item
03:51 that match that rule. Now I know there are other list elements
03:55 in there. So if I want all the elements that match
03:57 the rule, and I'm going to hit up all the way to the left.
04:01 So I'm hitting Cmd+Left to get to the left side.
04:04 And I'm going to hit the dollar sign to have two dollar signs.
04:07 Then, Cmd+Right to get to the right side and hit Enter.
04:11 And that gives me a list of all the elements that match that rule.
04:16 The console is also going to store the last used element in a special variable
04:19 called dollar sign, underscore. So if I type dollar underscore here, I
04:23 get the last selection. Now you can get focused to an element in
04:27 the DOM with the inspect method. So I'm going to grab this selector right
04:32 here that got the first list item and I'm going to type in inspect, and I'm
04:36 going to paste that in there. Now this is actually grabbing the element
04:43 in the elements tab. Notice that the LI is selected right here.
04:48 So it didn't just get the element, it actually got it and selected it from the
04:51 elements tab. You can ask the console to report
04:55 unevents when they happens. For example, you can execute a monitor
05:01 events command, and then type in a target.
05:05 So I can say document.getElementByID (SOUND) and then main.
05:12 And then put a comma and then click. So I'm going to look for click commands
05:16 in the main element of this DOM. So I'm going to hit Enter and nothing
05:20 looks like it's happening but I, if I happen to click anywhere within the main
05:23 element and the DOM, notice that it's reporting that as a click event.
05:30 And I can get information about the event by opening these triangles up.
05:34 Finally, if your console's getting a little bit messy, you can hit Ctrl+L to
05:37 clear the console. There's really a lot of power in the
05:40 Chrome developer tools. With complete access to and special
05:43 methods for manipulating the DOM, it's really the best place to explore the
05:47 inner structure of your documents.
05:50
Collapse this transcript
Communicating with the console through JavaScript
00:00 In the last movie, we saw how we can issue commands to HTML page from within
00:04 the browsers console. In this movie, we're going to take a look
00:07 at how to communicate with the console from within a JavaScript document.
00:11 So I'm going to go to the HTML document for this page.
00:15 And, at the very bottom, I'm going to add a script tag.
00:17 And that script tag is going to call a document called myscript.js.
00:28 Now, that document is inside an underscore folder and inside a JavaScript
00:32 folder, and it's called myscript.js. So, I'll save this, and then I can close
00:36 my index HTML document and work on the myscript.js file.
00:41 In the early days of JavaScript, the most common way of debugging your software was
00:45 through the alert message. It looks something like this and let me
00:49 go ahead and save this. Switch back to my HTML page and just
00:56 refresh the browser. You can see the alert comes right up.
00:59 That really gets your attention. But it's not very useful.
01:02 Especially if you're testing for things that happen often, like for example, a loop.
01:07 The more modern way is to send something to the console, so that we can monitor
01:12 things as they happen. So, you could use the console.log, command.
01:18 And it does sort of the same thing, but it doesn't pull up an alert.
01:21 So let's switch back to the document, let's go ahead and close our alert,
01:25 refresh, and nothing pops up, but in the console, you can see the message that we
01:29 typed in. Of course, that doesn't seem that useful.
01:31 But you can pass along any element into the console from the DOM.
01:35 So instead of putting in a message, we can type in document.querySelector and
01:39 pass it along any DOM element, so we'll pass along the element with the ID of
01:47 main and save this. Come over here, and refresh and now we
01:52 have that DOM element, and we can open that up just like if it was in the
01:57 Elements tab. There's actually a lot of other commands
02:00 you can send to the console. So for example, you can specify that this
02:04 information be given to you in a directory format.
02:07 If I say dir, I'll hit Save, come back here, refresh and we are getting a
02:12 different type of message that shows you all the methods and properties for that element.
02:18 You can also specify a type of formatting for your message by using different methods.
02:23 So instead of doing dir, you can do console info and I'll just type in here
02:29 some message, save it, and let me refresh.
02:34 You'll see that it's just sort of like same thing as the console log command.
02:38 But let's try a console.warn message. So if we come back here, and refresh,
02:46 we'll see that you get this little warning sign right here, plus the warning
02:49 sign down here. You're sort of forcing a warning into the console.
02:52 And also, of course, through an error instead of a warning and that should
02:59 really get somebody's attention. I'll refresh the page and see that it's
03:02 now in red and it has this little error message right here.
03:05 You can group a series of console commands into sections by using console groups.
03:10 So let me try that. We'll do console.group.
03:14 And we'll create different groups here. So we'll call this one Page Links.
03:20 And we'll issue a console.dir command here.
03:25 So there is just a forced directory structure so that it shows you the
03:28 messages and properties, and then we'll pass along a document.querySelectorAll.
03:36 It will ask for all the anchor tags. And then we'll issue a console.groupEnd
03:43 and that closes this group. So then we can start another group, we'll
03:47 do a console, and then do groupCollapsed message here.
03:52 It's very similar, we'll show you the formatting in a minute.
03:56 And we'll call this one Paragraphs, then we'll ask for a console directory command.
04:05 We're asking for document.querySelectorAll, and this time,
04:10 we'll ask for all the paragraphs, and then we'll issue a console.groupEnd...
04:20 Save that and switch over to the document, and refresh, and I can see that
04:24 we have a couple of messages. This one's already expanded, so that's
04:28 what the console.group command does. The console.groupCollapse actually
04:32 collapses it by default so this one shows you.
04:36 A list of nodes right here, and this one shows you pretty much the same thing
04:41 except that it's collapsed by default. So you can open this up and take a look
04:45 at the elements within. If you're trying to determine how long
04:49 something takes in your JavaScript document, you can ask the consult to log,
04:53 how long something took. So let's take a look at that.
04:56 I'm going to go ahead and start a timer by saying console.time.
04:59 Then in here, we'll issue a label called BigLoop.
05:06 And then we'll just execute some sort of generic loop here.
05:10 We'll ask for something to be from one to a million, just so that we can have some
05:14 time difference there. And, we don't really want anything to
05:18 happen in here. But then we'll execute a console.timeEnd,
05:21 and we'll pass it along the same label that we passed along up there.
05:28 They have to match, so we'll say BigLoop. Make sure you capitalize properly.
05:33 And then, I'm going to save this and come back into my document and refresh the page.
05:38 Notice that it's telling me that this label is taking 3.72 milliseconds.
05:42 So you can execute as many of these timers as you want within your JavaScript.
05:47 Just make sure that the labels match perfectly.
05:50 Another important debugging command is called the assertion.
05:53 So with an assertion, you can test for a condition.
05:57 If the condition executes as false, then it'll output something to the console.
06:02 So let's try that. So let's do a console.assert, and in
06:09 here, we'll just test something in the document.
06:11 So we'll do document.querySelectorAll, and we're going to check to see if there
06:18 are two navigational links here, so nav ol>li.
06:24 So, in the navigation, if the length of the elements within the selector is equal
06:30 to 2, then we say here, Sorry, there's only two menu items.
06:40 Let me go ahead and put this in double quotes here, because single quote here is
06:46 going to mess things up so, there, something like that.
06:50 So, is this executes to false? Then, it'll output this line right here,
06:55 which I know that my document has three lengths, so this should execute as false,
07:00 and we should see the error. So I'll save this, come back here,
07:03 refresh, and you can see that it says, Assertion failed, sorry, there's only two
07:08 menu item's, because there's three right up here.
07:10 So if we come back and we say, if the length of those is equal to 3, then we
07:16 won't get that assertion error. So the old-fashion alert message and even
07:20 console log have a lot of new cousins. A lot of these methods are also available
07:25 in other browsers. So there's definitely more options for
07:28 log and data from your scripts into the console.
07:31
Collapse this transcript
2. Selecting the DOM
Selecting elements with getElementById
00:00 In this chapter I'm going to go over the different methods for selecting DOM elements.
00:04 By far the most common is the getElementById method.
00:09 It allows you to select and element in the HTML file that is a tag that has a
00:13 single ID attribute. getElementById() expects to find only one
00:16 ID since an ID should appear only once in each document.
00:20 One common error that happens when accessing DOM elements is that people
00:26 type in getElementsById(), with an s, so make sure you watch out for that.
00:32 I really got to use a console.dir instead of console log.
00:36 It can help you find the methods and properties available to every node in the DOM.
00:41 So lets take a look at the DOM for a website in the console.
00:44 I got this page opened up on a browser and I am going to hit Cmd+Option+I to
00:48 enter the developer tools in Google chrome.
00:51 Now I'm in the Console tab but you can switch to the Element tabs if you want to
00:55 and take a look at the structure of this document.
00:57 It's pretty simple. Just an HTML document with a body that
01:01 has a wrapper, then a header and some sections as well as a footer.
01:06 So to use this method, you simply attach it to the document node since that's the
01:10 topmost element. I'm going to hit the Esc key to pull up a
01:14 console in the Elements tab. And I'm going to type in document dot get
01:20 element by ID, and I can see that the body tag of this document has an ID of
01:25 page home, so I can use that. So I'll type in page underscore home, and
01:30 go ahead and hit the Return character. And now I see only that node.
01:35 And now I can access only this specific node.
01:38 So I can open it up, just like in the elements tab up here, but I can see just
01:42 the data for that node. So right now this is the same as doing
01:46 document body, but with this method, you can target any element in the DOM with an ID.
01:53 So let's try to target the coming to events section which is right here.
01:56 A quick way to find out the structure of a specific element is by clicking on this
02:01 magnifying glass and then clicking on the element.
02:03 So I'll click anywhere on this element, I'll do the headline.
02:06 And now right here I can see the path to that item.
02:09 So I know that this headline is underneath an article with an ID of
02:14 coming to event. So I can type in document, get element,
02:20 by ID, and type in the name, coming to event.
02:25 When I hit Return I get just that node. Now its super typical to assign this node
02:31 to a variable so you can do something like create a variable call it mynode.
02:36 And make it equal to document.getElementbyId and then coming
02:40 to event. Now whenever I want to access that node,
02:47 I just need to type the name of it in the console.
02:50 Now this is the XML view of the node. If I want to see all the properties and
02:54 methods for this node, I can type in the DIR command and pass it mynode.
03:00 Now this shows me the same element, but I can see all the methods and properties
03:04 available to this node. There's all kind of good stuff in here.
03:08 So you can access, for example, the first child property.
03:10 So let's try accessing this. We'll go all the way to the bottom and
03:14 we'll just save my node dot first child. This comes up as having a text node as
03:21 the first element. This is probably not what you expected,
03:24 and that's because, in the HTML that we typed in for this document, we have a
03:28 carriage return. And it's picking that up as the child of
03:31 node instead of the H2 element. So if we take a look at child nodes,
03:37 let's try. My node.child nodes.
03:42 You can see that there is many elements. The first one is a text element and then
03:45 the second one is actually the age two tag.
03:48 You can see that there is also other text nodes right here and those are probably
03:51 carriage returns. Don't worry that these appear there right now.
03:55 We'll cover how to access some of these other properties and methods in an easier
03:59 way later. For right now, make sure you spend some
04:01 time playing around to access different IDs on your page using the magnifying glass.
04:06 And also try playing around with some of the properties on the notes that you grab
04:09
Collapse this transcript
Choosing elements by HTML tag
00:00 Traditionally, the easiest way to get to an element is by ID, but you probably
00:04 don't have an ID for every element in the DOM, or at least you probably shouldn't.
00:09 If getElementsByID is the most popular way to access things, then
00:13 getElementsByTagName is the next most popular.
00:16 GetElementsByTagName lets you access elements by their HTML tags.
00:20 It's super simple to use and returns an array.
00:23 So, notice that there is an extra S here. So, althought it's different than
00:27 getElementbyId, it can be used with it to create complex targets.
00:33 So let's take a look. So I'm going to come here to my documents
00:37 and I'm going to pull up the console. So I'm going to hit Cmd+Option+I, and
00:42 then I'm going to hit the Esc key. I'm on a Mac, so that would be
00:44 Ctrl+Option+I on a PC. So from here I can type in something like
00:49 documents get elements by tag name. And then ask for a specific tag.
00:56 So I'll ask for the List Item tag, and hit Return.
00:59 Notice that I get an array like element with a bunch of list items, and I can
01:04 open them up right here individually. So I can tell that this is the Home
01:08 element right here, this little Home link.
01:10 And if I get down further, I should see some other element.
01:15 So this is an artist's photo, I scroll up you can see it.
01:20 And actually I can select it from right here, I can tell that it's a little bit
01:23 further down. So that's that photo right there.
01:27 So, it grabbed every single list item in my document.
01:30 And that's sort of useful but, it could be a little bit better because we can
01:33 target a specific list item if one of its containers has an I.D.
01:37 So, if I wanted to go to this section of featured artists, I'm going to hit on
01:41 this magnifying glass and click on one of these.
01:43 Just so I can learn the pathway here. Here's the path.
01:47 I know that this has an ID of featured artists.
01:51 So I can combine the document, get element by ID, and ask for first the list
01:57 of featured artists. And then, within that, ask for the
02:03 getElements by tag name so that it returns only the list items within the ID
02:10 of feature artists. So if I hit Return I get just the list of
02:14 my artists. It's tough to keep on typing that so I'm
02:18 going to put it in a variable called my node.
02:22 And then I'm going to copy this right here.
02:26 So now, this is assigned to a variable that I can simply call by typing the name.
02:30 To get to individual elements, you can use an array notation.
02:33 So I can say, my node and then ask for a specific element, this happens to be the
02:37 third artist. Remember that arrays are 0 index, so item
02:41 2 is actually the third item. So, I can also type it in in its longer
02:47 form like this, gets me the same element. Every list element of the featured
02:53 artists has an image tag underneath it. So, we can easily get to it using the
02:57 first child attribute and we just type my node, the shortened version and type in .firstchild.
03:04 Now I have to make sure that I specify which node by typing in the array
03:08 notation and then .first child. So being able to access node elements by
03:13 tag name can be super handy, especially when you combine it with get element by id.
03:19
Collapse this transcript
Isolating elements by class name
00:00 So far, we've looked at picking elements by ID and tag name.
00:03 So, you're probably thinking that you can also pick elements by class name, and you
00:07 would be right, sort of. The getElementsByClassName function is a
00:12 bit of a new addition. Of course, it does that you select that
00:15 elements with a specific class, but because it is a newer selector it is
00:19 incompatible with older browsers. Whenever you have a question about
00:23 whether a browser has support for a method, you should check out a couple of
00:27 web pages. This one right here called caniuse.com is
00:30 a really good resource. So, if you scroll down you can see that
00:33 this method has support in pretty much every modern browser but not older
00:39 versions of IE. Another page you should check out is the W3C.ompatibilty.
00:45 If you scroll down on this page see you can get to the same information on the
00:48 get element by class name method. Now, I'm using a pretty modern browser
00:52 here this is a late version of Chrome so you shouldn't have a problem with this method.
00:56 So, I'm going to go to my website I'll click on the Artists section this time.
00:59 So, this page just has a list of artists right here.
01:02 And I'm going to break into the developer tools by hitting Cmd option I that would
01:06 Ctrl+Alt+I on the PC and then hitting the Escape key.
01:10 And then I can type in document. (SOUND) getElements, remember it's
01:14 plural, ByClassName. Then, I can type in the class name that
01:17 I'm looking for. So if you don't know the class name, you
01:21 can hit this magnifying glass. And just click on any one of these
01:24 images, and it gives you the whole path to that element.
01:28 So, this element has a class of artists, so I'll type that in.
01:34 And it returns every single artist on this page.
01:38 Now if you have to many items match in a class, say that you had two separate
01:41 lists of artists. You can get more specific by first
01:44 finding the element with the ID. So you could do something like document,
01:50 get element by ID, and then type it in first the ID.
01:54 So, we know that looking at the breadcrumbs we can see that this has an
01:58 ID of artist list, and then we can do get elements by class name.
02:09 So, this takes us to the same place but if you had multiple lists on the same
02:13 page with the same class, this might be a better target.
02:16 So as I mentioned earlier, this function is not supported on IE or earlier.
02:21 Because of this a lot of people have written their own implementation usually
02:25 called a polyfill of the get elements by class name method.
02:29 That's so that they can support older browsers.
02:31 If you want to check some of those out you may want to go to this URL right here
02:35 this page is put together by John Resig creator of jQuery.
02:40 And it compares the different methods that people use to support older
02:43 browsers, and get elements by class name. Frankly, if you want to support really
02:48 old browsers. You may want to look into a library like jQuery.
02:51 It has much better class selectors, and a whole lot of other goodies.
02:55 I'm really surprised that this wasn't a function from the beginning in JavaScript.
02:59 It seems like a no brainer, especially if you already have a version that gets
03:03 elements by ID. It means that whether or not you use this
03:07 function depends on what browsers you want to support in your applications.
03:12
Collapse this transcript
Querying CSS to select elements
00:00 Selecting elements can be a little bit of a pain with JavaScript.
00:03 You can select things by ID, tag name, and on newer browsers, by class name.
00:08 If you're familiar with CSS, one of the best ways of isolating elements is by
00:13 using a newer function called querySelector.
00:15 querySelector and its cousin, querySelectorAll let's you choose
00:19 elements by using CSS-like notation. This let's you pick nodes through CSS selectors.
00:23 That's super similar to the way that jQuery works.
00:28 So, if you're familiar selecting things with jQuery, you'll be right at home with this.
00:32 Now, this is not compatible with older browsers.
00:35 But it does have a little bit better support than get elements by class name.
00:39 Notice that it's supported by IE8. This is super easy to use, and probably
00:44 the best way to select elements in HTML. So, I'm going to go to this HTML document
00:49 and pull up the developer tools. So, I'm hitting Cmd+Option+I, that's
00:53 Ctrl+Alt+I on a PC, then hitting the Esc key to pull up the console.
00:57 Now, here, I'm going to type in documents.querySelector, and then put in article.
01:04 This is going to return the first element on my page that matches the selector in
01:11 CSS notation. If you want to select every element that
01:14 matches your selector, you can use the cousin function, querySelectorAll.
01:20 Now, there's a difference between these two.
01:22 This one returns an array like list with the results, and that's super important
01:26 to remember because you access array-like stuff differently.
01:29 So, you can do something like this, querySelector, and choose article, and
01:34 then pick the childNodes, and that gives you all the children nodes of this
01:39 article element, that happens to be this article element right here.
01:42 But you can't do querySelctorAll childNodes, that's because query selects
01:50 are all returns on arrays. So, you have to specify which article
01:53 you're referring to. Notice that when I come up here, I know
01:55 that this is the first article, and this is the second article which is the
01:59 featured artist section, right here. So, if I wanted to target this and get
02:03 all the childNodes for this section, I have to add an array of one right here.
02:08 Remember, arrays are zero index. So, element one is the seconds element,
02:13 which may be what we want here. So, if I hit enter, now I can get all the
02:17 featured artist children. Now, you can obviously get classes in
02:22 your document like this. So, let's go to the artists page and get
02:25 a list of all the artists. I'll click on artists right here, then I
02:29 can do document querySelectorAll, in this case, because I want all of them.
02:35 And then, instead of typing in just the name of a tag, in quotes I can put in the
02:40 name of a class, which would start with a period, and then something like artist.
02:45 So, just like with CSS, you can also use things like type selectors.
02:49 So, I'm going to go to the register page. And I'm going to do a document, querySelectorAll.
02:59 And in here, I'm going to type in input, and then type=checkbox.
03:06 And it actually looks like I need to type in radio, because I don't have any check boxes.
03:12 Let me change that to radio here. And that's going to select all of my
03:16 radio elements within the form. I can also choose a descendant, so let's
03:22 try something like document.querySelectorAll.
03:27 And then, in here, I'll type in an ID of artists list, and then a descendant like
03:35 a list item. So, I hit return, and I get all the list
03:38 items within artists lists which are these elements over here.
03:42 I can also get a child, so let me add to this list item a child of image.
03:48 And that gets me just the image tags. I can also ask for multiple items in the
03:55 same list. I'm want to do document querySelectorAll,
03:58 and then I'll ask for all the images. And after that, I'm also going to get.
04:03 From the comingtoevents section, all the images as well.
04:08 And that's going to give me all the images for the artists, as well as this
04:11 phone right here, which is the image in the comment to event section.
04:15 So, by far, querySelector is the easiest way to get to elements.
04:19 If you don't care about supporting browsers older than IE8, then you're in business.
04:23 If you really want to support very old browsers, you may want to look into
04:26 something called a Polyfill. A Polyfill is a way of supporting newer
04:31 methods in older browsers. And here's a really good list of a bunch
04:35 of HTML5 cross browser Polyfills. You can also go to this page where you
04:40 can find a lot of other Polyfills. Now, if you really have to support other
04:44 browsers, you should check out something like jQuery.
04:47 Which gives you a lot of other selectors. In newer browsers, you are safe with
04:51 something like querySelector, and querySelectorAll.
04:54
Collapse this transcript
Working with named form elements
00:00 Selecting form elements is a little easier because forms can have and
00:04 additional attribute called Name. Like with document images, the DOM
00:08 provides a special object called document.forms.
00:12 That's an array of form elements on the page.
00:14 You can also get to any form element that has a name a little bit easier.
00:18 So, let's take a look. I'm going to go over to my website, and
00:22 I'll click on this Register page. Now from here, you can see that I have a
00:27 form on the left side of this document. Let me pull up the developer tool by
00:31 hitting Cmd+Option+I on a Mac, Ctrl+Alt+I on a PC.
00:35 And then, I'm going to hit the Escape key to pull up the console, and I'll type in document.forms.
00:41 Now, that gives me an array of all the forms in the current document.
00:46 I've only got one form, so it's only returning one item.
00:48 If I want to get into that element, I can say document forms and then the index.
00:53 Since this is the first item, I'm going to use the index 0, because arrays
00:57 are 0 indexed. Now, I can get to the elements within the form.
01:00 Now, since the form itself has a name, you can get to the form directly using
01:06 dot notation. So, instead of doing that, I can just
01:09 simply do document.register. And if I hit Enter, I get to the same
01:14 place, a little bit quicker. Now if you open this form up, you can see
01:19 that a lot of these elements have name attributes.
01:21 So, for example, I can get to the 'my name' field by typing in document,
01:25 register and then my name. You can easily change the form fields
01:32 value with the value attribute. You really have to be careful with forms,
01:40 because there's a possibility of two input fields having the same name.
01:44 In that case, you're going to get back an array.
01:48 Although its pretty easy to get form elements by name, you can also use a
01:51 special function called "get element by name".
01:56 So, you can document.getelementsbyname, and then get to subscribe and the zeroth element.
02:07 In that case, it returns the first Radio button which is right here.
02:11 You can change which of these fields is selected by choosing the checked attribute.
02:15 So, I'm going to choose the second element, which would be element one and
02:19 then select the checked attribute, and set that to checked.
02:26 That chooses the second element. For popup lists, you can get to the
02:30 select element with the name property. So, you can say something like
02:34 document.register.reference, and that gets you to that item.
02:40 If you want to pre-select an item, you can also do it directly by setting the
02:44 valley to one of the existing values. So, if you look at this form, you can see
02:48 that we have the Option of a friend, Facebook and Twitter.
02:51 But this doesn't actually matter, what matters is the values of these fields.
02:54 If I opened up the select field, we can see that here I have a value of friend,
03:00 Facebook, or twitter. So, I can go to document, register,
03:03 reference, and then set the value to Facebook.
03:06 That picks Facebook from this list. There's also a property called selected
03:12 index, it returns the Option currently selected.
03:15 So, instead of doing this, I can choose Document register reference, and then you
03:20 selected index. That tells me that the third element is
03:24 currently selected. Remember that this is an array index, so
03:28 the second element is actually element number three.
03:32 There's a lot more to working with forms, so if you get a chance check out my
03:36 course on form processing and validation.
03:39
Collapse this transcript
Understanding nodeType, nodeName, and nodeValue
00:00 Every DOM element has a few important properties you can use to identify the node.
00:05 So we're going to take a look at some of those properties in this movie.
00:09 So, for example, the nodeType property gives you a numerical value of a node.
00:14 The nodeName property gives you the name of the node, usually the tagName.
00:19 So for example an anchor tag would have a type of A.
00:22 Node.atrributes is a how you can access attributes inside a node.
00:26 So if you were inside an anchor tag you could ask for a list of attributes and
00:31 get the href attribute. Also the node value let's you access an
00:35 element inside a node. So let's take a look at these in an
00:38 actual document. So here we are in our sample file.
00:42 I'm going to hit Cmd+Option+I, Ctrl+Alt+I on the PC and then hit the Esc key to
00:46 pull up the console. So I'll start out by creating a variable
00:50 called myNode, and then assigning it an element in our page.
00:54 In this case, I'm going to choose the last link in our navigation menu, which
00:59 is right here, so we'll type in document.querySelectorAll.
01:04 Find the navigation list item anchor tags.
01:11 And then choose the last element, happens to be element number 4.
01:14 So, once that's in a variable, I can type that in.
01:17 And note that I have to write element. Now, let's type in myNode.nodeType.
01:26 So that it's returning a value of one. You get a one because this is a normal
01:31 element to node. Each node in the dome has different node type.
01:36 It can be anything from a element to a text attribute or other node.
01:40 You can find out more about node types on this page right here.
01:45 If you scroll down here to the bottom you can see the type of node types by numbers.
01:49 So that notices that a normal element node is type number one.
01:53 You have attribute nodes, text nodes, and then a bunch of other sort of weird nodes.
01:57 You're definitely going to use element nodes, attribute nodes, and text nodes.
02:01 You can also find out what a node is, by asking for the node name.
02:06 So this is telling you that this is an A element, or an anchor tag.
02:10 Now you can get to any attribute within this node by using the attributes array.
02:14 So I can say myNodes.attributes. And now it's giving you a list of the
02:20 attributes inside that node. Notice that I only have one attribute
02:23 here called href, so it's only returning one item which is right here.
02:28 So to get to that, we would type in myNode attributes and then the 0 element.
02:34 Now we can find out the node type of this attribute as well.
02:36 So we can say something like this and then say nodeType and notice that this is
02:41 type 2. And if you remember from this page, type
02:45 2 is an attribute node. You can also get the node name, and that
02:52 returns the fact that this is the atra function.
02:54 So sometimes you want to get to all the properties or attribute within a node,
02:58 and you can access them through this array.
03:01 Now if you want to, you can go one level deeper and get to the text of the link.
03:05 So I'm going to say, myNode first child. Now the first shell seems to be the text
03:11 for this link, called register. But let's make sure and try typing in the nodeType.
03:18 Now this is type 3 so we'll go back into our list of nodes here and note that this
03:22 is a textNode, it's not text, but a textNode.
03:26 So you may think that you can do something like mynode.firstChild and set
03:31 it something like registration to change the text inside that first link.
03:36 That doesn't work. That's because the first child of the
03:39 node is a node of type of text node. It's not a text element so its not real
03:45 text so its just another node. Like another element inside our DOM tree.
03:49 To actually get to the text we have to type in myNode.firstChild and then use
03:55 the nodeValue attribute. Then we can set that something like
04:00 registration and that changes our link right here.
04:04 What you have to remember is that technically everything in the dom is a
04:09 node including text elements. So to get to the text of a node we have
04:14 to use the first child and then we have to access the value by going to the node
04:18 value property. So as you learn to manage and control
04:22 your nodes, you'll need to get familiar with these different properties.
04:25 They'll let you not only access but also manipulate your DOM nodes.
04:30
Collapse this transcript
Traversing up and down DOM nodes
00:00 As we saw in the previous chapter, Java Script has a number of DOM selection functions.
00:05 However, once you have the element it's important to understand how to move up
00:09 and down the node tree. Every node in the DOM has a series of
00:13 properties that you can use to move up and down the node list.
00:16 So for example, you can use parent node to go up a level and get to the parent of
00:20 an existing node. Child node is an array of all the
00:24 children of the current nodes. So any sub-nodes of the current node.
00:28 You can use firstChild and lastChild as a property and acts as the first and last
00:33 element of the children of the current node.
00:36 Finally, you can also use previousSibbling and nextSibbling to move
00:40 within elements that have the same parent.
00:42 So, let me show you how this works. Here's our document and I'm going to go
00:46 into the developer tools, then hit the Esc key to get into the console.
00:51 So, first off I'm going to assign a node and our DOM to a variable.
00:55 So, I'll say variable my node is going to be equal to document.
01:00 I'm going to use query selector and then I'll choose the class of artist list and
01:06 find the first LI element. Remember a query selector chooses only
01:10 the first element. So right now we're looking for this
01:13 artist list right here and only the first list item that has this image.
01:17 Now it's really convenient when I can see the breadcrumbs on how to get to this element.
01:22 So it's really useful to click right here on this magnifying glass and then click
01:26 on an element. That shows me right here, bread crumbs to
01:28 that element. So I can see that, there's an image
01:31 inside this list item. And this is the list item that I have
01:34 selected right here. So if I hit Enter.
01:38 And I type in myNode, I can see this list item just the first one because this is document.querySelector.
01:45 If you type in the dir command and you use myNode, you're no longer going to see
01:49 the node as an XML or HTML file, you're going to see the node.
01:53 And then if you click on this triangle you'll be able to see all of the
01:56 different properties available. So you can see things here like child
01:59 nodes and other things like parent node, right here.
02:04 So let's try accessing the parent of this node.
02:07 So we'll say my node. That parent node.
02:11 Now it's going to take us up one level to the node that has the entire list.
02:17 Now, that's this level, right here. Of course, you can go the other way by
02:21 accessing the child nodes. So we can say, get me the parent's nodes
02:25 children by selecting my node.parentnode and then selecting child nodes.
02:30 Child nodes is an array like object that you can use to access elements inside the
02:37 current node. Now you may notice something peculiar
02:39 about these child nodes. Everything in the HTML document is a node
02:44 including text. And you can see that when we check these
02:46 nodes we have some text embedded into these elements.
02:50 These are probably white based characters like carriage return and tabs that I've
02:54 typed into my HTML document. They actually appeared as children of the
02:58 parent node. You're probably expecting just a list
03:02 items and that can sometimes be a problem.
03:04 And we can get to the first and last element in a node sequence because they
03:09 have special keywords called firstchild and lastchild.
03:12 So let's try to get the parent node that first child.
03:16 And sure enough we're getting a text element not the first list item but the
03:20 first text element. And the same way we can check for the
03:23 parent nodes last child. And that gets us another text node.
03:28 Probably a carriage return at the end of this list.
03:32 Now you can navigate through different siblings, by using the next sibling and
03:36 previous sibling. Let's try going to the parent node, and
03:40 then we'll access the first child, and then we'll use next sibling.
03:46 And this is probably what you were expecting when you did first child, you
03:50 got the second element. If you look at this array the first
03:53 element is a text node, the second element is actually the list item.
03:57 Of course, you can go the other way with previousSibling.
03:59 Now you may use something like childNodes, siblings, firstChild and
04:03 lastChild to loop through a series of elements.
04:06 But the text node problem could be a pain.
04:09 It would have probably been better to go back into our query selector and just
04:13 choose Query Selector All. That would give us a list of only the
04:19 list items. And we could loop through that array
04:21 without having to worry about any text nodes.
04:24 So navigating through the different nodes with some of these node selectors may
04:28 seem like a good way to go through the elements.
04:30 But frankly it's a lot more trouble than it's worth.
04:33 There's an easier way to navigate through these elements, but of course there's a cost.
04:37 And I'll show you how to do that, in the next movie.
04:40
Collapse this transcript
Targeting node elements
00:00 In the last movie, we talked about basic access properties for node elements and
00:04 the problem with traversing the DOM nodes using child nodes.
00:08 Sometimes you get text elements that are just carriage returns.
00:11 Some browsers support a better way of selecting elements.
00:14 So, for example, you can use the property called first element child, and that
00:19 gives you the first child only if it's an element.
00:22 Like a tag. So, it would ignore any comment or text nodes.
00:26 You can also use, of course, last element child and children.
00:30 Which gives you only children that are elements.
00:34 Of course, you can also use previous element sibling and next element sibling
00:38 that's the equivalent of the previous sibling and next sibling.
00:41 Now, before you get too excited about this, this has really lousy browser support.
00:46 So, if you go to this page and you take a look at this right here, it's showing you
00:50 that its available in IE 9 but not in some versions of Firefox.
00:54 So, it's something good to use for newer browser support but not something you
00:58 should be using if you want to be totally backwards compatible.
01:01 So, let's take a look at some of these. So, I'm in my document.
01:04 I already have the consulant open. So, I'll click right here on the
01:14 magnifying glass and we'll click on this element that shows me the path.
01:18 And if I do my node, you can see that we have only the first list item over here.
01:23 So, you can see that my node.parent node. We get the entire list.
01:27 Now, if we do my node.parent node, and then try to get the child nodes of this
01:35 element, we're going to get everything including every carriage return.
01:39 Now, if we do only parent node than that children, we're only going to get the
01:45 children that are elements. So, it's going to ignore all these
01:47 characters right here, which is pretty awesome.
01:50 Of course, you could do my node parent node, and then do first child.
01:56 That gives you the first text element. But if you do first element child, it
02:02 will ignore the first text element and give you only this element right here.
02:05 And the same way you can use my node, parent node and then last element child.
02:13 And that gives you only the last element, getting rid of any text nodes.
02:17 And, of course, you can traverse through the different nodes using next element
02:21 sibling and previous element sibling. Now notice that we didn't have to do
02:25 anything special for parent node. And that's because a text element or a
02:29 comment cannot have any children by definition.
02:32 So, pairing node is always going to return an element.
02:36 So, although this is a great way of selecting just elements, you need to ask
02:39 yourself if you're willing to sacrifice some support in older browsers.
02:44
Collapse this transcript
3. Modifying DOM Attributes and Content
Changing HTML attributes
00:00 Once you select an element, there are a few ways you access the attributes within
00:04 that tag. The easiest is by using dot notation.
00:07 So, for example you can access the source attribute of any image by using something
00:11 like img.src. So usually, dot notation lets you just
00:16 put the name of the attribute next to the node.
00:19 These are read and write properties so you can change what an existing image is
00:22 pointing to if you want. You just add it to a new value.
00:25 You can even add attributes that don't currently exist in the dot.
00:30 One thing you have to be careful with is that some attributes, like say the class
00:33 attribute, are reserved JavaScript words. So, they have to be handled a little bit differently.
00:39 So, let's take a look at this in an actual document.
00:41 Just to get started, I want to target this element right here.
00:45 It's an image inside a list. So, I'm going to pull up the developer tools.
00:49 And hit Cmd+Option+I, that's Ctrl+Alt+I on the PC, and then I hit the Escape key.
00:55 I want to get to this element, so I'm going to click the magnifying glass just
00:58 to make it easy for me to visualize where that element is.
01:01 And select the element right here. And gives me the breadcrumbs.
01:04 And I know that I can get to this element by going to the artist, list, class.
01:08 And then finding any image inside it. So, I'm going to set up a variable called
01:13 my node and set that to document query selector, and in here find the class of
01:22 artists list and the first image. Query selector will only get us the first
01:28 image in this list. If I hit enter I'll type in my node.
01:32 And, sure enough, I've got just that first image.
01:36 This node has two attributes. The src attribute and the alt attribute.
01:40 So, let's see what we get when we type in mynode.src.
01:45 We get the location of the image file. Since these are read and write
01:49 attributes, we can change the image this file is pointing to.
01:54 So, I'll try mynode.src and I'll use the equal sign to set it to something else.
02:01 That replaces that image with another image.
02:05 That means that we can also add any attributes we want.
02:07 We could for example, add an id name to this picture.
02:10 So, I could say something like mynode.id, and then set it to, Select it.
02:17 Now lets go ahead and pull up mynode and see what attributes it has.
02:20 You can see that the selected attribute has been added right here.
02:24 Just using the attribute name in dot notation is going to work for most attributes.
02:29 But, there are some exceptions because, some attributes are the same as some of
02:33 JavaScript reserved names. I mentioned class because class is a
02:38 reserve word in JavaScript. So, we can't just say mynode.class equals myclass.
02:47 That doesn't work even though it looks like it worked, if we pulled again the
02:50 node, we'll see that it didn't add that class.
02:53 So, we have to use something called class name, so we can say my node dot class and
02:59 then name. You can actually see it in the pop up
03:01 list right here so you can pick it from that class name.
03:05 Would then equal something else. Something like myclass.
03:09 And now we've added that class name. Notice it's already showing up right here.
03:14 But we can pull the mynode again and see that it's been added as an additional class.
03:17 So, labels are another good example of this issue.
03:20 Let's go over to the register form, and if we pull up the magnifying glass and we
03:25 access one of these labels right here. And I am going to change my variable,
03:30 mynode to point to one of those labels. Now this should pick up the first label
03:38 and notice that, that label has a for attribute.
03:41 For in JavaScript is usually used to create loops, so we can use the value for here.
03:47 In that case we have to use something like mynode.html and then capital For.
03:58 And lets check out mynode, and you can see now it has the new For value.
04:02 The change a Boolean value like our radio button, you can use the keyword and then
04:08 a true or false or a one or a zero. So lets try that.
04:10 Let's go ahead and reset mynode again, and we've got a radio button down here.
04:16 Let's go ahead and target it with the magnifying glass.
04:19 So, we'll just ask the query selector to go fetch an input field with the type of radio.
04:30 Now you gotta be careful how you do this one, because I can't have single quotes everywhere.
04:37 I need to combine double quotes on the outside with single quotes in the inside,
04:43 so that it doesn't get confused. So, let's try mynode again, and we see
04:47 that it has the right input field. And what we could do here is just say mynode.checked.
04:53 And we can use the value true or false here.
04:56 I'll set it to zero, which will be false. That means that that element is no longer
05:01 automatically selected. So, let's check mynode.
05:05 And even though that value is checked, we were able to set it to be unchecked.
05:10 (UNKNOWN) notation makes it easy to select elements but because you have to
05:14 stay away from reserved words, sometimes its not as easy to remember.
05:18 Also with that notation there's no way to delete attributes.
05:21 We'll take a look at another way of handling that in the next movie.
05:25
Collapse this transcript
Working with restricted attributes
00:00 The quickest way to work with element attributes is to use the dot notation.
00:03 That's not always convenient because sometimes attribute names like class or
00:08 for can be restricted in JavaScript. But there's another way of doing it.
00:12 JavaScript provides a few functions for dealing with attributes.
00:15 So, for example, you can use the getAttribute method to get the value of
00:19 any attribute in an element. If you set attribute you can set the
00:24 value of an existing attribute. You can check to see if an element has an
00:28 attribute function. Finally, you can remove an attribute with
00:32 the delete attribute function. So let's take a look at these in a document.
00:37 Here's our web page. I'm going to go over to the registration
00:40 page, and I'm going to pull up the console, Cmd+Option+I, Ctrl+Alt+I on a
00:45 PC, and then hit escape. And then I'm going to create a variable
00:49 called My Node, and pass it, and element in my DOM.
00:53 (SOUND) So, I'm going to test that out. And you can see that I have the first
01:02 label which has the word name in it. That has an attribute of 4 and we usually
01:07 use that in JavaScript to create loops. So, we just can't use 4 in dot notation.
01:12 We would have to use htmlFor, and that would work.
01:17 But for any of those attributes names that have funky names because they might
01:20 be reserved words, it's easier to use some of these other functions.
01:24 So, let's try getting the attribute for for, we'll use myNode and say
01:28 getAttribute (SOUND) and type in for. That gives me the same thing, and I
01:35 didn't have to remember the weird name, html4.
01:39 To set an attribute, you can pass it to parameters.
01:41 So let's go ahead and change this for attribute to something else.
01:45 We'll use set attribute, and we'll pass it the four value because we want to
01:48 change the for attribute, and then we'll just set it to something else.
01:54 Hit Return and pull out myNode again. And now you can see that it has the value somethingelse.
02:01 In addition to that, you can find out if a node has an existing attribute with the
02:04 hasAttribute function. So we use myNode and ask if it has an
02:09 attribute of ID. And, of course, that returns false
02:14 because it doesn't have an attribute of ID.
02:16 So if I ask if it has an attribute for, then it returns true.
02:21 Finally, of course, it can remove an existing attribute.
02:23 We can use my node and then remove attribute.
02:29 And passed the attribute that we want to renew.
02:30 For, and that get's rid of it. So let's check my node and return.
02:35 And there it is. It now has no for attribute.
02:38 So though these are a little bit harder to use than dot notation, they're more
02:42 reliable and work with any attributes that might be restricted JavaScript names.
02:46 So, sometimes it's just easier to use these methods.
02:49
Collapse this transcript
Detecting data attributes
00:00 In an HTML document, a developer can type in any attributes, even if they don't
00:04 necessarily exist and pretend they're valid HTML.
00:08 The browsers usually ignore them, but validaters will flag these as not being
00:12 normal HTML. This is the HTML for the document we've
00:16 been working with. And if I want to, I can add a coolness
00:19 attribute here and set it to whatever I want.
00:23 Now, the browser is probably going to ignore this attribute and not do anything
00:26 with it, but if I try to validate my document.
00:29 I want to copy this and I'll switch over to the WC3 validater.
00:33 And I'll click on the Validate By Direct Input tab, and paste my code right there.
00:37 And I'll hit the Check button, you could see that it's telling me that there's at
00:41 least one error there. Let me scroll all the way to the bottom,
00:45 and notice that it says attribute coolness not allowed on element image at
00:48 this point. It really means that it doesn't know
00:51 anything about this new attribute that I just invented.
00:53 So, thankfully HTML5 provides a way of adding special data attributes, so that
00:59 if you want to you can create your own while remaining valid HTML.
01:03 You simply create an attribute with a name that starts with data, you add a
01:07 hyphen then any other name that you want. So, for example, you can use an attribute
01:12 called data-coolness, and neither the browser or the validators will have a
01:16 problem with it. If you want to access it, the
01:18 node.dataset property lets you get to these using JavaScript.
01:23 So, let's take a look at how that works. So, for example, on this page, I want to
01:27 get to one of these images right here, because I've added a special attribute
01:31 called data task to some of these speakers.
01:33 So, I'm going to get to the console. And I'll hit this magnifying glass and
01:39 click on, I'll click on this second image.
01:41 I think that has the right attribute. Notice that that one has a data task of speaker.
01:48 And that's really the one I want to target.
01:51 So, what I'll do is I'll create a variable.
01:55 And this time I want to choose queryselectorall because I want to get
01:58 all of the images. And I'm going to hit Return, type in
02:05 myNode and hit Enter. You can see a list of every one of the presenters.
02:09 Notice that some of them have a data task attribute.
02:13 So, if I want to get the value of that attribute, first I need to make sure that
02:16 I have the right target. So, if I say myNode and I want to get the
02:19 second element, which is element one, because I raised our 0 indexed and that
02:25 gets me to that element. So, I can say something like
02:27 myNode1.dataset, and use the name after the hyphen, right here, so just call it task.
02:38 And it let's me know what the value of that is.
02:41 So, if I want to set that, all I have to do is give it a name right here.
02:46 I'll call this presenter, presenter. And that modifies the value of that node.
02:54 So I can set it back, just as easliy. Now this is really handy in accessing
03:01 elements in projects created with frameworks like jQuery mobile, because it
03:05 heavily uses the data attribute to set things.
03:08 However, it does have spotty support in browsers.
03:11 If you really want to be safe, you should probably use the set and get attribute
03:15 functions for data attributes. Although this is a really handy function,
03:19 I would probably stay away from it at this time, because of lack of support in JavaScript.
03:23 Still if you're trying to make your own tags, you should probably use the data
03:26 attribute itself, it's a really good idea.
03:29
Collapse this transcript
Controlling classes with the HTML5 classList
00:00 One peculiar aspect of the class attributes is that you can add not just
00:04 one but as many classes as you want to any HTML element.
00:08 So, modifying classes by using dot notation or even the set attribute method
00:13 is not convenient if the element has more than one class.
00:16 Thankfully, HTML5 adds a new property to the dom called a class list.
00:21 This is a new object that is going to be added to all the nodes in your DOM.
00:26 It allows you to do jQuery like modifications, class attributes.
00:29 So for example, you can add, remove, or toggle classes.
00:33 Unfortunately, it has pretty lousy support in Internet Explorer.
00:36 So if we check caniuse.com, you could see that it's only supported in IE 10.
00:42 As I mentioned, you can use the add method of classList to add a class
00:46 without disrupting any existing classes in the document.
00:49 You can use remove to remove a class without affecting any other existing classes.
00:55 If you use the toggle method, it'll turn a class on or off.
00:58 First time you call it, it'll add the class, the second time you call it, it'll
01:02 remove it. You can also find out how many classes an
01:05 element currently has, as well as whether or not an element contains a specific class.
01:10 So, let's take a look at this in a real document.
01:13 So, here I am on the page for my website and I'm going to scroll down to this area
01:17 right here and I'll pull up the console. And I'm going to hit the magnifying glass
01:22 to access this first element. So, here we can see the path to that element.
01:26 So, first I'm going to create a variable and assign it to this down element.
01:32 I'm going to target an image in the div that has the artist list class.
01:43 Let's check that out my node and there it is.
01:47 We've got the right node which is that element.
01:50 And if I want to add a class, all I need to do is save my node.classlist, and then
01:53 use the add method, and pass it a class. So, that added the class faded, you can
01:57 see it right here in the breadcrumbs. And if I pull up my node again, you can
02:08 see that it's there as well. So, if you use add again and add a
02:13 different class, you can see that both classes are added.
02:18 You can see a red there in the breadcrumbs, and you can also see it if
02:22 we call up the node. To remove a class, you use remove.
02:30 Now, it only has the faded class. Let's go ahead and remove that one as well.
02:36 If you use toggle, it'll turn a class on and off, so let's check that out.
02:39 Let's toggle right here, and we'll call a class called hidden.
02:44 First on my call it, it hides it, it returns also a true value.
02:49 And if I call it again, it shows it and it returns a false.
02:53 You can also use contains to find out whether or not the element has a class,
02:59 since we just took off the class hidden it returns false.
03:03 This is a really handy way and super similar to the way jQuery lets you manage
03:07 your class names. It's so convenient that it's worth using
03:10 a Polyfill to give you access to it right now.
03:13 So, you may want to check out this GitHub page for a good Polyfill that allows you
03:18 to use this in older browsers.
03:21
Collapse this transcript
Targeting the attributes property
00:00 Another way you can get access to attributes inside your nodes is through
00:03 the attributes property. Once you retrieve this property, its
00:07 values can be accessed in a number of ways.
00:09 So you can look for them by numeric index, also by named index or dot notation.
00:15 So, let's take a look at how that works. So here's my file, I'm going to get into
00:19 the console, and I'll create a variable that accesses a specific node instance.
00:30 Let's test my node, and it has the first image, and that is this image right here.
00:35 So, we can get to all the attributes inside this image by using my node and
00:41 then type in attributes. When we hit Enter, you see that we have a
00:45 node map, and it's a list of all the attributes in numeric order.
00:49 Now this is a pretty interesting object, because it has attributes of both array
00:54 elements, and also objects. So, you can get to the source attribute
00:58 in a number of ways. It's the first attribute, so it would
01:00 have an index of zero. And that works like an array.
01:04 You can also get to it by using source or SRC as the key.
01:08 You can even get to it by using SRC in .notation.
01:14 Unfortunately, these are read only values.
01:16 So ,you can't really set them this way. It does give you the ability to read
01:19 attributes as a list, which could come in handy in some projects.
01:24
Collapse this transcript
Using text content modifiers
00:00 There's a number of properties that allow you to change the content related to a
00:04 node as HTML. The most common and oldest is innerHTML.
00:08 It also has the most support in browsers. In newer browsers, you can also use
00:13 outerHTML, which will include any tags within the current node.
00:17 There's also a new function that lets you insert some additional HTML within a
00:20 specified node. It's called InsertAdjacentHTML and it
00:24 takes two parameters. First, a string that determines the
00:27 insertion point and then the HTML. So, let's take a look at these.
00:31 I want to switch over to my document, and pull up the developer tools and the console.
00:38 So, I'll start by creating a variable called mynode, and then targeting a node
00:41 in the DOM. Now this time, I'm going to target the
00:45 text node right here that has this article.
00:49 So, I'm going to hit this magnifying glass and click right here on this headline.
00:53 That tells me the path to that node, which I know is going to be an article
00:56 with the ID about the event. So, let me check out that node, and sure
01:02 enough, I got the entire article. Notice that it has article tags.
01:08 So, if we open this up, you can see there's an H2 right here and a paragraph.
01:12 So, we can get the contents of the node with the innerHTML property.
01:16 So, we say mynode.innerHTML. It's going to give us everything inside
01:21 that node. Notice that it's not including the
01:23 article tags, just whatever is inside the article tags.
01:26 It's a read and write value, so we can set it to anything we want.
01:35 And you can see now, I've replaced this article with this content right here.
01:38 There's a newer property introduced by HTML 5 called outerHTML.
01:43 And in browsers that support it, it also includes the tags of the element that was called.
01:48 So, let me go ahead and refresh this page.
01:51 And I'm going to click on the console and hit the up arrow a few times to get to my variable.
01:56 And then I'll hit enter, and I know have that node again.
02:00 And if I say, myNode.outerHTML, notice that includes the article tag.
02:08 There's also a new function that lets you insert some additional HTML within a
02:12 specified note. It's called InsertAdjacentHTML, and it
02:16 takes two parameters: a string that lets it know the insertion point and then the
02:20 actual HTML we want to insert. So, let me try that one.
02:28 So, we need a string right here and then something we want to insert.
02:32 I'll put in a paragraph right here. The string that I put in here will be one
02:38 of four values. And that will determine the position of
02:43 the element within the DOM. So you can say, before begin, after
02:47 begin, before end, and after end. Let's try the after end property here.
02:54 You notice that it added this paragraph right here.
02:56 So, if I say something like, before begin, it'll add it at the top.
03:05 So, let's try doing another one. After begin, and this time I'm going to
03:10 add a word right here. Notice that it added this after the first element.
03:20 And in the same way we can do before end. This time it was added before the last element.
03:30 So, although these are pretty cool, it does require newer browsers.
03:33 So, most of the time people stick with innerHTML.
03:36 It's by far the easiest, safest and most common way to access content within a node.
03:41
Collapse this transcript
Modifying elements as text
00:00 Although you can modify the content of notes as HTML text with the inner HTML
00:05 property, there's a few other ways of doing it.
00:07 However there's some really big browser issues here.
00:10 Let's take a look anyways. You can use the innerText property to get
00:14 just the text of the node. However you have to use textContent if
00:18 you're using Firefox. That means that if you want to access
00:21 just the text of a node, you're going to have to do something like this in JavaScript.
00:25 If the text exists within the inner text property, then you can set your text to that.
00:31 Otherwise you'll have to use the Firefox version.
00:33 So let's take a look at this in the dom. We'll start by getting an element from
00:37 the dom, we'll place it in a variable called my node.
00:45 So right now we're targeting this section right here called about the event.
00:48 If you want to, you can click on the magnifying glass and click on that headline.
00:52 Let me go ahead and hit enter and test out my node.
00:57 And sure enough, it has the whole article, now if we do a direct version of
01:02 this, we can see the different properties available to that node.
01:08 Right next to the innerHTML property, we have a property called innerText.
01:13 If you look at it carefully, you'll see that it's the same text as innerHTML,
01:17 without any of the HTML tags. So if I type in my node, that innerText,
01:22 and hit enter, you'll see that it's just the text of that node.
01:28 So I imagine that if I wanted to get just the text of some content, this might be a
01:33 really convenient way to do it. This is a read and write property as
01:36 well, so you can set it, if you want to. I'm not really sure how useful that is
01:44 because it'll wipe out any sort of formatting or syntax you worked really
01:48 hard to put in there. Also this version, as I mentioned, is not
01:52 supported by Firefox. Firefox has a similar property you can
01:55 use called Text Content. But, unfortunately, Text Content is
01:59 supported by everything except for Internet Explorer.
02:02 So if you want to use these, you'll have to create some if-then statements.
02:06 A check, which property, the current browser supports.
02:09 This is the type of thing (LAUGH) that can give you a headache as a web
02:11 developer, so I would probably stay away from these.
02:15
Collapse this transcript
4. Inserting and Deleting Nodes
Creating and appending nodes
00:00 So far we've been looking at ways of selecting and modifying DOM elements.
00:04 Next we'll be taking a look a creating DOM elements that have never existed before.
00:08 Creating new nodes is super simple. The create element method lets you add an
00:13 element to the current document. Once you create the element though, it
00:16 exists in memory, but it's not apart of the current DOM.
00:20 The append child method is used to add the element as a child of an existing node.
00:26 So let's take a look at this on a page. On this homepage, I've taken one of the
00:29 authors out of my list. So let's go ahead and add here back in.
00:33 First I'm going to turn on the developer tools, by hitting Cmd+Option+I,
00:37 Ctrl+Option+I, on a PC, and then hitting Esc.
00:40 And let's go ahead and move this up a little bit so we can see them all.
00:44 And what I want to do is click on the magnifying glass and find the author
00:48 right next to the missing author, right here.
00:50 And if you look at the elements panel you could see that the, author that's missing.
00:55 Has a list item, but there's no image tag inside the list item, like the other authors.
01:01 So first we need to create an image element using the Create Element method.
01:05 Let's go ahead and make a variable here. We'll call it MyElement.
01:09 And I'm going to set it to the document and call the Create Element method and
01:14 pass it along the element that I want to create.
01:16 So what I need here is an image tag, I hit Return.
01:19 You can see that my element now has an empty image tag.
01:24 So, obviously this element is going to require some attributes.
01:27 We can insert those with the set attribute method or by simply using dot notation.
01:32 So let's try that. We'll do my element.
01:33 Obviously I'm going to need a location of the image file and that's going to be in
01:38 the images folder under artists. And then the name of the person LaVonne
01:45 LaRue, and now and then jpeg, plus we need to add an Alt tag.
01:53 So this time I'll do myElement.alt and that's going to be syntax which just says
02:00 photo of LaVanne LaRue. Okay, so, let's take a look at my element now.
02:07 So, it has the image tag plus the source and alt attribute.
02:12 This particular artist has non standard HTML attribute of data role speaker.
02:18 So, we're going to use the set attribute method for this one since I can't use dot
02:22 notation to access a non standard attribute.
02:26 So, now I'm going to use set attribute, and I'll pass along data, task, and speaker.
02:35 So, now if we take a look at my element and see that it has all the attributes
02:39 that it needs. So you might be wondering why we're not
02:42 seeing anything on the screen. And that's because a new DOM element can
02:46 exist in memory but it's not really a part of the DOM until we put it in an
02:50 existing location. So I need to insert this element inside
02:53 the list item tag that doesn't have an image.
02:56 So since we're going to need to find that I'm going to create a variable called
02:59 myNode and look for that element. I'll go to document and use
03:04 querySelectorAll and what I want to look for is the artist list.
03:08 The unordered list with a list item. So, I'm using the querySelectorAll and
03:15 that's going to find all of the list items within the artist lists.
03:19 If you look at your breadcrumbs, you can see that the artist list class Is right
03:23 above our list items and it has the entire list so let's go ahead and hit
03:27 enter here. And if we take a look at my node now so
03:31 let's do a directory my node and we'll open this up.
03:38 You can see that the one that we need, should be this list item, number 6.
03:43 So if I kind of, select it, you can see it right here, in the DOM.
03:47 So I need the list item with an index of 6.
03:51 So what I'm going to do is, access myNode and, specifically the sixth element, and
03:57 then type in append child. And the name of the element we add which
04:01 is that list that we created earlier. One I do that, it's going to add the
04:06 image right where it needs to be right here.
04:08 So, creating notes is really not a big deal but adding them to the dom means
04:13 understanding a lot of what we've learned so far in previous movies.
04:17 Of course sometimes it's easier to use inner HTML.
04:21 Just add some HTML, so, in most applications, your going to need to
04:24 decide what option you want to to use.
04:27
Collapse this transcript
Controlling node insertions with insertBefore
00:00 AppendChild is a great method, but you don't always want to place an element as
00:04 a child of another element. You need to be able to insert notes at
00:08 any position inside a node list. If you watch the last movie, we sorted of
00:12 cheated a little bit by already having a list item element, in which to place our image.
00:17 That made it easier to use appendChild, but thankfully there's a great function
00:21 called Insert Before that lets you place a node in a precise location.
00:26 Let's take a look at that in a document, so this works a lot like a pen child.
00:30 Before we use it I need to get into developer tools, so Cmd+Option+I,
00:35 Ctrl+Alt+I on a PC, and then Esc. Now what I want to do is add a new
00:40 paragraph in our venue, travel section. So let me click on the Venue/Travel
00:45 section first and scroll down to right here.
00:48 I want to put it right in between these two paragraphs.
00:51 So I'm going to grab the magnifying glass.
00:53 Click on one of these paragraphs, and there I am.
00:55 I want to put that right before. So first we are going to create the
00:58 paragraph element. I will create a variable called pNode and
01:03 make that equal to a new element, so document.createElement and we want to
01:10 create a paragraph element here. So I had written I have got my paragraph
01:15 and now I need to create a text node for insertion into this paragraph so I will
01:18 create a new variable call it myText. And this time I'm going to create a TextNode.
01:32 And now we need to append the text to our paragraph node.
01:37 So this time I'll go ahead and use appendChild.
01:40 So the pNode and appendChild, then I'll pass along my TextNode.
01:45 So let's check out pNode right now. It should be a paragraph with the text
01:51 that we specified. So in order to insert that in between the
01:54 two paragraphs, we'll need to grab the location of the venue section.
01:58 So I'll create another variable, this time I'll call it new node.
02:02 And I'll use query selector to find the element with an ID of the venue.
02:09 Now that we have the node we need to analyze it a little bit.
02:13 So we'll do a directory in this newNode and check out what's inside.
02:21 So if we take a look, this article has seven child nodes.
02:25 Now a lot of them are going to be text nodes that are just carriage returns.
02:28 Here's the first paragraph, and here's the second paragraph.
02:32 So what we want to do is insert a new paragraph before node five.
02:37 Which is the second paragraph, so what I'll do here is use this new node that I
02:43 created and then say insert before. What I want to insert, which is pNode,
02:50 the paragraph, and then insert it into new node and then childNodes and I'll
02:57 want to place it before child node number five.
03:01 So when I hit return, it should add that paragraph in between those other two paragraphs.
03:06 So insert before is definitely a more surgical insertion than appendChild.
03:10 It's much easier to use when we want to insert things in specific place in the
03:14 node list, it's the only way to go.
03:16
Collapse this transcript
Cloning and removing nodes
00:00 Making a copy of a node is called cloning and it can be useful if you want to move
00:04 things around in your DOM. Let's say that you want to dynamically
00:07 change the position of an existing element, the cloneNode method lets you
00:12 make a copy of an existing node with our without its children.
00:15 You can then reposition the node anywhere within the existing DOM.
00:20 You can use removeChild to delete a note from the DOM, but you've gotta be careful
00:23 with this one. RemoveChild works by removing a node from
00:26 an existing parent. So if you want to use it, you've got to
00:29 call it on the parent of the node you want to delete.
00:33 So, let's take a look at this in an actual DOM.
00:36 So, we've got our website right here. I'm going to pull up the console and I'm
00:40 going to create a variable called my node and make it contain a node that's
00:45 going to have the artist lists which is right here.
00:48 So, I'm going to hit the magnifying glass and click on one of these items.
00:51 You can see the breadcrumbs pointing to that element and when we create the
00:57 variable we'll use querySelector. And call the element with the class
01:02 artist list. So, be careful here.
01:06 You want to make sure you use querySelector, not querySelector Alt, or
01:10 you'll get an array of all the elements. So, let's check out what my node has.
01:15 So, this has the entire list of artists right here.
01:19 To clone an element you create a new node and use the clone node method, then you
01:24 pass it along a true or false value. If you pass along a true value it means
01:28 that all of the child nodes will also be copied as well.
01:31 So it's perfect for copying something big, like our list of artists.
01:35 So I am going to make a new variable here call it new node.
01:39 And I'm going to make it equal to my node, and then use the clone node method,
01:44 and pass along the valley of true. So by passing true, I'm not just copying
01:50 the node, I'm copying the node and all its children.
01:52 So I hit Enter. Now let's check out this new node.
01:55 We'll go ahead and issue a directory command on this new node.
01:58 So we'll hit Enter and we can analyze this node.
02:01 You can see that it has all the children from the previous node.
02:06 So I want to insert it before the my schedule promo on the homepage so lets
02:10 take a look at that. So we have got coming to that event here,
02:13 and we have got this schedule area right here.
02:15 That's where we want to put it so I am going to hit the magnifying glass once
02:18 again and just click on that area right there.
02:21 And we know by the breadcrumbs that we want it right around this area.
02:25 So let's go ahead and target this insert location.
02:29 So we'll create another variable, call it insert location and I'm going to make it
02:36 equal to document. And then I'll use query selector.
02:42 And we want to ask for the entire sidebar element.
02:45 So, we'll do a pound sidebar that targets this sidebar element right here, which
02:52 contains all the different pieces. So, this top piece right here coming to
02:55 the event, as well as this other scheduled piece.
02:59 So let's go ahead and investigate this new sidebar element we've got now.
03:02 So do a directory on insertLocation and take a look at that.
03:08 So if we open this up we can see that it has seven child nodes and the schedule
03:14 child node happens to be element number four.
03:16 So we want to insert it right before element number four.
03:20 So let's check that out right here. There's the beginning of that element.
03:23 We want it to be right here. So I'm going to scroll all the way down
03:27 and go to our insertLocation and then use the insertBefore method and then pass it
03:37 along the new node, as well as the place where we want to insert this.
03:43 We want it to be in the insertLocation and then look for child nodes.
03:51 Element four. That looks pretty good, but I've got a
03:54 couple of duplicate nodes. It would be great to remove the original
03:58 nodes, and to do that we can use the method called remove child.
04:02 So, you think there'd be a function that just removes an existing node.
04:04 But remove child works by removing a node from a parent.
04:08 So I need to use it not on my node, but on the parent of my node.
04:12 So let's check that out. We'll do myNode, which is the original
04:17 node and then parentNode and say removeChild myNode.
04:23 This is a little weird. Once you get your head around this, you
04:26 can remove any node in the DOM. Now the node containing my original list
04:31 of artists is gone. So hopefully you are getting comfortable
04:34 managing your DOM. These two methods are really crucial to
04:37 understanding how to move things and change things within your existing DOM.
04:41
Collapse this transcript
Replacing existing nodes
00:00 In the last movie, we learned how to move things around in the DOM by cloning and
00:04 then removing a node. If you're just trying to replace an
00:06 existing element then there's a function that does just that.
00:09 replaceChild lets you take a node and replace it with another node.
00:11 Since it's replacing a child you have to call it from the parent node, so it can
00:18 be a bit confusing to use. This method is more convenient than
00:21 cloning and replacing. You don't have to delete the original node.
00:25 So, let's take a look at this in our project.
00:27 So, I'm going to pull up the console. To replace a node, we need to get both
00:30 the node we want to move and the one we want to replace.
00:33 So, I want to move this same list of artists, right here.
00:36 I'm going to click on a magnifying glass. Click on one of these just to get the
00:40 path right here. And these very useful bread crumbs that
00:43 kind of tells us where we're at. So I know that this whole section is
00:47 called featured artists. So that's what I want to move.
00:50 This time I don't just want to move the photos I'm going to take this whole section.
00:53 So first I'll create a variable here called my node.
00:57 I use query selector and I want to get that entire list of featured artists.
01:04 So I'll get the element with the ID of featured artists.
01:07 (SOUND) And again, you want to be careful that you use querySelector, not
01:12 querySelectorall, or you'll get an array of element, even if it's the only element
01:17 in the page with that ID. So, next, I'm going to do a variable for
01:21 replaceNode and I'm going to find document.querySelector.
01:28 And this time I'm going to look for the item comingtoevent.
01:32 So, this is the item that I want to replace.
01:35 And so if I look at that, let's see this is coming to the event.
01:37 So I want to replace this feature artist with coming to the events section.
01:42 So, I can show you where that is. Click on the magnifying glass,
01:45 click-right here and it tells you there's the I.D.
01:48 that we're looking for coming to event. So hit Enter.
01:52 So now you can just issue a replaceChild method.
01:55 Just like cloning, we have to replace the child in the parent node for it to work.
01:59 So here we go. We'll use replace node.
02:03 And then we'll say, I want to get the parent node of this element and replace child.
02:09 And what I want to do is replace my node with this replace node and the position
02:16 that we want to replace with. And when I hit Enter (SOUND), I've
02:18 replaced this section right here with this section called featuredartists that
02:23 I imported from my node. So that's a pretty fast way of moving
02:27 things around. ReplaceChild saves you the step of having
02:30 to delete the original node.
02:32
Collapse this transcript
5. The DOM in Action
What we'll build
00:00 So, in the next series of movies, we're going to be building a very simple dom
00:03 related project. We're going to be going to the artist
00:06 page, and if you scroll down a little bit, there's a list of artwork from these
00:10 artists that are in the show. If you click on it, this is going to pull
00:13 an overlay which grays out the background.
00:16 And then an image. This same image is going to resize
00:19 vertically or horizontally, depending on its dimensions.
00:23 This is a seemingly simple task, but it requires quite a bit of JavaScript to get
00:27 it right. So, if we take a look at the finished
00:29 version of this code. You can see that the HTML is pretty simple.
00:34 Scroll down here and you'll see that assisted list of images with an image tag
00:39 inside each one of those list items. Now, in the JavaScript, you can see that
00:44 what we're doing is selecting a specific node of this document's dom.
00:48 And then adding an event listener that waits for a click inside this node.
00:53 We could have added an onclick event on each of the images, but this way we can
00:59 just capture an event that happens in the entire node and then ask where the target
01:04 of that click is. In this case we're going to check to see
01:06 that, the click has happened inside an image tag.
01:09 If it does, then we're going to create an overlay and then we're going to style the
01:14 overlay with CSS. We're going to worry about the position
01:18 of the overlay to make sure it centers on screen.
01:20 And then we're going to add an image inside the overlay which is this part
01:25 right here. Now we need to wait until the image has
01:28 loaded to make sure it resizes to the accurate size of the screen.
01:32 The image is too tall. And it needs to size a certain way.
01:35 If it's too wide, it needs to size a different way.
01:39 We'll also have to worry about centering the image on the screen.
01:43 There's a couple of other utility functions that we'll need to worry about.
01:47 We'll need to make sure that we close the image if the big image is clicked on, and
01:51 that we delete the events that we created, as well as remove the overlay.
01:55 You see quite a bit of the things you've been learning on this course in this JavaScript.
02:00 Finally, we'll worry about things like window sizing, and what happens when
02:04 somebody scrolls in window. Finally, we've got a function right here,
02:07 that centers the image. Although this seems like a simple task,
02:11 we're going to put a lot of what we learned in this course into action.
02:15
Collapse this transcript
Adding a bubbling event listener
00:00 So let's go ahead and work on this project.
00:02 Right now I'm on the artist's page of this website.
00:05 And what I want to do is target this section right here with the art from each artist.
00:11 I need to make sure that I create a node that targets this area right here.
00:15 And then add a listener for that node that checks for a click.
00:18 If one of these images is clicked then we're going to execute some code.
00:22 So I'm going to switch over to my code and show you that this is a very simple
00:26 list right here, that has image text inside each list item.
00:31 So right now my java script code is completely empty.
00:34 First I will start off by creating a sell executing function.
00:37 So just protect any of our local variables from anything else running in
00:41 our page. So start by creating a variable called
00:49 myNode and then I'm going to set it to document.querySelector and I'm going to
00:56 target a section in my page. Now what do I need to target?
00:59 Let's go back into this page and pull up the console and what I want to do is
01:03 target this section. So, to find out where that is, I'm going
01:06 to click on the magnifying glass and click on one of these items.
01:09 This shows you the breadcrumbs down here and what I want to pay attention to is
01:13 the fact that I have an article with an ID of artlist.
01:17 Inside that I have a div with a class of pixgrid.
01:20 And inside that I have an on ordered list.
01:22 That's really what I want to target. So, let me switch back here and target
01:25 the artlist and then target the pixgrid and the on ordered list within that So
01:36 once I have that node, I can add an event listener to it.
01:40 So I'll save my node, in at event listener, and I want to check for a click
01:47 event when it happens in that node. So once that click happens I want to
01:52 execute a function. That function is going to pass along an event.
01:56 And I want to make sure that I pass this value of false right here.
02:01 This makes sure that the event is bubbling properly.
02:06 Bubbling just refers to the fact, that I want to target things within this on
02:10 order list, and not target things outside it.
02:15 So for right now I'm just going to go ahead and log to the console our event.
02:19 Just so we can see what's happening. So let me go ahead and save that switch
02:23 over to my code back to the console and I'll refresh the page.
02:28 And I'll click somewhere inside here notice that no matter where I click its
02:32 going to log the event of the console. Now, if you look right here you can see
02:35 where I'm clicking. So if I click somewhere kind of in the
02:38 middle its going to say that I clicked on the list item if I click.
02:41 In one of these photos is going to show a click in the image.
02:45 I want to target only the clicks in the image.
02:48 So if I open this right here you can see there's a bunch of properties.
02:52 The one that I'm interested in is the target property right here, which is there.
02:57 If I open that up, I can see a lot of different things in here.
03:00 But, I can choose one that's down here called tag name.
03:05 So I can check for this property called tag name.
03:07 And if that property happens to be image, then I can execute my function.
03:12 So let me go ahead and switch over back to my code and fix this to check to see
03:18 if the target, so e the event, target of the event happens to have a tagName of IMG.
03:26 Then, I want to perform a set of tasks. (SOUND) For right now, I'm just going to
03:34 output it to the console. So I'll paste that in here, save it, and
03:42 come back into my page. Refresh, and this time I'll click on this image.
03:47 You could see that the event fired. But if I click right here, it's not
03:51 going to fire an event. So it's only firing an event if I click
03:55 on an image inside this unordered list. So you can see that by creating a node we
04:01 can be very specific by only targeting things within that node.
04:04 So in this case I check for the tag name of IMG.
04:08 And now we're ready to handle our overlay.
04:10
Collapse this transcript
Creating and styling an overlay with JavaScript
00:00 So, in this movie I want to show you how to create an overlay.
00:04 We're going to use a lot of things that we already used in previous movies.
00:07 So, first off, I'll remove this console lock command.
00:10 And what I want to do is create a variable and call it myoverlay.
00:15 And in here I want to create a new element.
00:16 So, I'm going to use the Create Element method.
00:20 And create a new div in our document. So, just so that it's easier to target, I
00:24 want to make this overlay have an id of overlay.
00:28 I can do that by just using the dot notation and pass an empty attribute.
00:32 In this case the id that I want to change and then I want to add this to the
00:36 current document so, I'll just add it to the body tag and use the Append Child method.
00:46 And pass along my overlay so, what this'll do is once you click on an image
00:51 its going to add this overlay to the end of the bodytag, so let's go ahead and go
00:55 into our code. So, here we are in the artist page.
00:58 And I'm going to scroll down and click on one of these items.
01:01 It doesn't look like anything happened but I am going to break into the console
01:04 and I will go into the Elements tab and notice that its showing the overlay right now.
01:11 So, let me refresh the page and show you that, it's not there right now but if I
01:14 click on one of these images. It'll appear right here.
01:17 That's pretty cool, it doesn't look like anything yet, so we need to go back in
01:21 here and add some styles to that. So, I'm going to set up the overlay styles.
01:28 So, I could obviously add some CSS to my stylesheet, that automatically takes care
01:32 of that overlay. But, this is a course on JavaScript, so
01:35 I'm going to show you how to style everything in JavaScript.
01:37 First I'll set the position of this element.
01:41 So, my overlay.style, cause we'll be working with style sheets and then we'll
01:45 change the position property of the styles to be absolute.
01:51 Okay finally we'll modify the top property to be zero to begin with.
02:00 And then I'll make this overlay have a background color.
02:07 Now notice that whenever I do an attribute that normally would have a
02:10 hyphen in CSS I need to camel case it. So, the b right here is lowercase and the
02:16 C is uppercase. So, I'm going to create a background
02:19 color and that's going to be equal to a rgba color because I want it to be
02:23 partially transparent. And that can be just black plus 70% of
02:28 the color, so that's going to be 70% black.
02:33 And then, I'm going to create the style of the cursor, to be a pointer.
02:38 That'll be nice, so that when somebody clicks on this, it'll get the pointer.
02:41 And they'll know that when they click on the image that we're going to insert here
02:45 later, they can go back into the regular page.
02:48 Alright, now we need to position this properly.
02:50 So, I'm going to say re-size and position overlay and I'll start by modifying the
02:58 width of my overlay. That's going to be equal to window inner
03:02 width plus since this is CSS we have to include a measurement system here so
03:12 that's going to be pixels. Alright so next I'll do the same thing my
03:18 overlay style and then adjust the height. Be equal to the window, enter height plus
03:29 the pixels. So, see that's working I am going to save
03:33 this go back into my project refresh and I will click on one of these images.
03:40 Now notice that the overlay is working but is sitting at the very top.
03:44 If I scroll all the way to top I can see it and that's not really what we want.
03:48 We want it to follow along with the position of the window.
03:51 So, we go back into the code and we need to add a couple of lines here,
03:55 myoverlay.styletop is going to be equal to the window.
04:02 And then page Y offset will be the offset from the top, plus the pixels and then
04:12 same thing for the overlay style Left window.page X offset.
04:21 In this you got to be careful here about capitalizing properly, make sure this is
04:25 a lower case right here. Now we got the adjustments for this
04:30 scroll, we save this and go into our page on refresh, and when I click on these,
04:36 notice that it's the proper height.
04:39
Collapse this transcript
Adding an image
00:00 In the last movie we created an overlay and placed it on top of our window.
00:04 What we want to do now is add the image on top of that overlay.
00:08 To do that we're going to need to figure out where our large image is.
00:12 Now if you take a look at my project you can see that I have a bunch of images here.
00:16 When I click on one you see the overlay, but I need the big image right here.
00:19 So my images have been very carefully saved in the same folder as the other images.
00:24 So you could see here, here's the artwork section.
00:27 So if I got a thumbnail called Baird Bellingham_tn.jpeg the large version of
00:33 the image is the same name without the underscore thumbnail.
00:37 First I need to find out he name of the item that I clicked on.
00:41 That is stored in the event target. You can see right here that we were able
00:45 to figure out the tag name of the image by querying the event target.
00:49 And then the property tag name. So right over here.
00:52 I want to create a new variable. I'm going to call it Image source.
00:59 And I'm going to set it to the event target, and the source of that event target.
01:06 So let's go ahead and just output that to the console, so we can see it.
01:09 Console, log and then I'll output the e.target.
01:15 Switch over to our project, I'm going to refresh and I'll click on one of these
01:19 images and then I will show the console. And notice that whatever image I click
01:25 on, it's going to show me the element and the source attribute is going to have the
01:29 location of that image. It's going to have the location of the
01:32 thumbnail, so we'll need to worry about that in a minute.
01:34 So we refresh, so we see that if I click on another image, it outputs the target,
01:39 which is the note that has that image. Let's go back into our code.
01:42 Let me go ahead and delete this console log.
01:45 So I'm storing the source or the location of the current target into this variable
01:50 I called Image source. So I'm going to create another variable
01:53 called Large image. And that's going to be a new element that
01:59 I'm going to create, so I'll do a document.createElement, and a create a
02:02 new image element (SOUND). I'm going to give this an ID, so
02:05 largeImage.id is going to be largeImage. And I'm going to set the source of this
02:17 new image element to be equal to my old image source and I want to do a sub
02:27 string method here. The substring method will take a string
02:32 and allow me to truncate part of that string.
02:34 So what I want to do here is say, 0, start at the 0 position, and then find
02:41 the image source, and take the length of that -7.
02:48 So that is, whatever the image name is, without the _tn.jpg.
02:53 And then just add the word, jpg, to it (SOUND).
02:58 That way, we'll get the location of the high-resolution image.
03:02 Now we'll modify the style of this image. So we'll set the display to block.
03:10 Just like we would in css, and then we will set the position to absolute.
03:14 Finally I'll pin this new image to the overlay.
03:20 So I'll save my overlay dot appenchild and then I'll pass it this large image.
03:29 So I'm going to go ahead and save this. Come over here, I'll refresh the page and
03:34 then click on one of these images. You can see the big image comes in, it's
03:37 not centered, it's too big, but at least it's coming in properly.
03:41 So if you click on any of these you should be able to see the large version
03:45 of the image. And that's all we want to do in this movie.
03:48
Collapse this transcript
Resizing images in the DOM
00:00 And the last movie, we were able to place the images onscreen, but they're way too huge.
00:05 We need to adjust them to fit within the size of the current window.
00:08 So, what I want to do is re-size the images.
00:10 The problem is, I can't do this before I finish loading the image.
00:14 If I try to calculate the size of the image before it's loaded, it's going to
00:18 assume that the image doesn't have any size.
00:21 I need to make sure that I create an event that waits until the image is
00:24 finished loading and then calculates its size.
00:28 So, I'm going to take this off right here, and I'm going to add sequence that
00:32 the image has loaded. I'm also going to add another comment up here.
00:46 So, right down here, I need to add an event listener.
00:49 So, I'm going to target my large image and then add an event listener.
00:53 I'm going to look for the load event and execute a function once the image has loaded.
01:01 And what I want to do is check to see the image is taller or wider, so will do a
01:07 re-size here if the image is taller. And I want to check the height of this
01:15 image after it's loaded, and see if its bigger than the windows in our height.
01:24 If it is, I want to calculate a ratio of the size of the image divided by the
01:27 image that I'm trying to load in here. So, I'm going to save this, ratio is
01:34 going to be equal to Window, enter Height, divided by this, which will be
01:39 the current image that I clicked on, height.
01:44 If it's true that this image is too tall, then I'm going to adjust the height to be
01:49 equal to the height of the current image times the ratio that I just calculated.
01:56 Now, I'm going to do the same thing for the width.
02:01 So, if the image is wider, I'm pretty much going to do this right here and just
02:09 change some of these variables. Once this is calculated, then I can add
02:18 my image. So, I'll add it to the overlay once again
02:21 by appending the child of the large image.
02:24 So, let me go ahead and save this, and try it out in our browser.
02:28 We'll refresh and I'll click on one of these images.
02:31 And now you can see that it's re-sizing the image, to the height of this image
02:35 cause this image is particularly tall. So I'll refresh, and click on one of
02:39 these other ones. You can notice that this ones a good
02:43 size, so it's not going to be a problem. And this one is tall, so these are coming
02:48 in just fine. That is important to note that when you
02:51 are working with images, sometimes you have to wait until after the image loads
02:55 before you start performing some functions.
02:59
Collapse this transcript
Centering an image
00:00 So our images are loading, everything is resizing properly.
00:03 Now it's time to center the images. to do that, I'm going to create a
00:07 separate function, and it's going to go right down here, right before the closing
00:11 of the self-executing function. So I'll call this function center image,
00:18 and this function is going to expect an image to be passed to it.
00:23 So, what I want to do here is start by creating a couple variables.
00:27 I'll call this myDifX and that's going to be equal to the window interwidth.
00:36 Minus the image that gets past, width, and divided by two.
00:43 Once we have re-sized, the images they are going to be usually smaller or the
00:48 same size as the window. So, we need to calculate the difference
00:51 between the width of the image and the window.
00:54 Divide that by two so that if it needs to be moved.
00:57 It's going to be moved by half the distance.
00:59 That's what places it in the center. So, we'll calculate the difference
01:03 between the x position and the y position of the images.
01:06 So, instead of when or with here this will be inner height, and this will of
01:13 course be the image height divided by two.
01:17 Once we have that then we can say the image style, because this is going to be
01:23 a style sheet attribute that we're changing here.
01:25 It's going to be equal to, myDifY, plus, because this is CSS, pixels.
01:34 And then, the same thing for the image left.
01:38 And what we'll do here is we'll just return the image.
01:46 So I'm going to save this, and I need to do one more thing.
01:51 I need to actually call this function. So, this function will take care of
01:54 centering an image that passed to it. But of course, I need to call it somewhere.
01:59 So, I'll do it right before I append the image.
02:01 So right here, we'll say, center image. And we'll pass it, this, remember that
02:07 this in this case is going to be the large image.
02:10 So, let me save that, go into my page, refresh and click on one of these.
02:15 Right here, you can see that the image is now in the center of the screen.
02:18 I'll refresh again and I'll click on any one of these images and they should all
02:23 be centered. So, I'm refreshing in between.
02:25 The next thing I need to do is build something.
02:28 That handles clicking on these images, so the images disappear and I can see my
02:33 screen again. We'll do that next.
02:36
Collapse this transcript
Handling clicks
00:00 In the last movie, we were able to center these images inside the overlay but there
00:03 is no way of getting rid of them. If I try in to click on any of these,
00:07 nothing happens. So I need to check for an event when I
00:10 click on these images that gets rid of the overlay and the image and shows the background.
00:16 So let me go ahead and do that. I'm going to come of here and into my code.
00:20 And right here I'm going to addEventListener to the largeImage.
00:24 So, largeImage and addEventListener. I want to listen for a click here and
00:29 once the click happens, execute a function and that function is going to do
00:33 some stuff. I also need to make sure that I pass it
00:37 false so that it bubbles properly. And in here I need to check that this is
00:42 going to happen only when the overlay exists.
00:47 If the overlay exist what I want to do is remove the overlay.
00:51 To remove the overlay, you have to use the removeChild function.
00:54 You have to remember that removeChild doesn't work on the node itself.
00:58 It works on the parent of the node you want to remove.
01:01 So you have to say something like, my overlay.parent node.
01:06 And then remove child. And then remove my overlay.
01:09 So let me go ahead and save this, and refresh the page.
01:13 Now, click on one of these. And then, if I click on this image again,
01:16 it'll get rid of it. Important thing to remember that remove
01:25 child always works on the parent of the node you want to remove.
01:29
Collapse this transcript
Adjusting for scrolling
00:00 So our page is looking really good. If we click on one of these images,
00:03 everything looks great. Centered on the screen, top of the overlay.
00:07 I can click on it to make it go away. But there's a little bit of a problem.
00:11 If I click on one of these and I scroll the window.
00:13 You can see that the overlay doesn't move with the scroll.
00:16 And that looks a little funky so we're going to fix that next.
00:19 Let me go back into my code. And right here I'm going to listen for a
00:24 window event when somebody scrolls the window.
00:27 So I'll say window, addEventListener, I'm looking for a scroll event.
00:32 And once that happens I'm going to execute a function.
00:36 And I'm going to return false so that it bowls properly.
00:41 And in here I'm going to first make sure that I have the element called myOverlay.
00:44 Because I don't really want to adjust anything unless that element exists.
00:49 So I'll say, myOverlay style top. And I'll set it to the window.
00:55 Page YOffset plus pixels because this is CSS.
01:05 And then do the same thing for the overlay style left window page XOffset
01:13 plus pixels. So let's save that and see if it's working.
01:16 Back into our page, refresh the page, click on one of these elements and try
01:21 scrolling the window. And now you can see that that moves with
01:23 the scroll of the page. And let me go ahead and click that out.
01:27 So sometimes you really have to pay attention to these kind of details by
01:30 really messing around with the structure of the page to make sure you catch
01:33 anything that may cause the user some grief.
01:35
Collapse this transcript
Detecting and adjusting for a window resize
00:00 This project is working and looking great.
00:02 But there's a slight problem that we need to take care of.
00:04 If you resize this window for any reason and then I'm going to click on one of
00:09 these, it looks great. But if I resize my window now, you can
00:12 see that it doesn't look good because the overlay doesn't stretch to the whole
00:16 width of the window. So we need to go ahead and fix that.
00:19 I'm going to go enter my code and, right over here, I'm going to add a listener
00:24 for another window event. So this time, the event that I want to
00:29 look for is called resize and, of course, like before, I want to execute a function
00:35 and pass it along false to make sure that it bubbles properly.
00:39 Once again, we're going to make sure that the overlay exists.
00:43 And if it does, we need to adjust this. So, my overlay style, we're going to
00:47 change the style attributes width and we're going to make that to the window
00:52 inner width plus the pixel measurement. (SOUND) We're going to do a similar thing
01:00 with the height. (SOUND) Of course, it's going to be inner height.
01:04 (SOUND) And we also need to adjust the position of the top and left of the overlay.
01:07 (SOUND) So, I'm going to save this. And I'll go back into my project.
01:12 I'll refresh. I'm going to make my window smaller again.
01:17 And I'll pull up one of these images, resize my window.
01:21 And the overlay looks really good but the image is not centered.
01:24 So let me go back here and just execute the center image function and pass it
01:29 along to large image. So now, I'm going to make my window
01:33 smaller again and I'll refresh click on this and as I re-size the window, the
01:38 image will be centred. One more thing that I want to clean up is
01:42 when I remove the 'overlay' I want to make sure that the window is no longer
01:46 listening for the events that I have just created.
01:49 So, I'll add a 'window, removeEventListener' here and pass it
01:51 along the event that I want to remove. Which will be re-size, window, and false,
02:01 because of the way the event bubbles, and do the same thing to get rid of the event
02:06 that the text for scroll. This is just a clean-up function, it's
02:10 going to work either way but, it's safer to do things properly.
02:13 So I'll save, refresh, re-size the window, and try it out once again.
02:21 Everything's working well. Click on this, and it goes away.
02:24 And now our project is finished. So hopefully you got a chance to practice
02:28 a lot of the things that you learned in this course.
02:30 Enhancing the DOM is all about understanding how the DOM nodes work, so
02:34 you can access them, remove them, and create events around the nodes that you
02:38 have in your DOM.
02:40
Collapse this transcript
Conclusion
Next steps
00:00 Thanks for watching this course, I had a great time putting it together.
00:03 There's a lot of really good information on JavaScript on lynda.com online
00:07 training library. I consider this course part of a series
00:11 of courses that I've been focussing on related to JavaScript.
00:14 So for example, this course on JavaScript and JSON as well as this other course
00:19 with JavaScript and AJAX. I've also created a course on Validating
00:23 and Processing Forms with Javascript. That might be a great next course,
00:27 especially if you're interested in the Dom and forms in particular.
00:30 Finaly, I've also put togrther this course on Building Facebook Applications
00:35 that focuses on HTML and Javascript. And has a lot of goodies in there,
00:39 including how to work with JSON to bring in different feeds of data into your
00:43 facebook application. I covered a lot of resources on the
00:46 course, and you may want to check them out a little more in depth.
00:48 So for example, you can check out caniuse.com for information about the
00:53 different type technologies and their support on different browsers.
00:57 So the Java script, API, is down here, you can kind of click on those and take a
01:01 look at some of the support in different browsers.
01:03 Another great website is HTML5please.com. It has a lot of information on which Java
01:09 script and other techniques you should be using and which you should be avoiding.
01:14 So, if you click, for example on box-reflection, you can see why you
01:18 shouldn't be using this and learn more when you click on this link.
01:22 So, for example, here is the class list that we used in this course and you can
01:26 see that it points to this classlist.js polyfill, you can use to overcome this in
01:31 older browsers. Finally you should also check out this
01:34 W3C DOM compatibility guide. This has a lot of additional information
01:39 that some of the other lists don't have. On specific properties and methods of
01:43 Javascript and the Dom. So thanks for watching and have a great
01:46 time exploring the Dom.
01:48
Collapse this transcript


Suggested courses to watch next:


JavaScript and AJAX (1h 12m)
Ray Villalobos

JavaScript and JSON (1h 12m)
Ray Villalobos


Are you sure you want to delete this bookmark?

cancel

Bookmark this Tutorial

Name

Description

{0} characters left

Tags

Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading
cancel

bookmark this course

{0} characters left Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading

Error:

go to playlists »

Create new playlist

name:
description:
save cancel

You must be a lynda.com member to watch this video.

Every course in the lynda.com library contains free videos that let you assess the quality of our tutorials before you subscribe—just click on the blue links to watch them. Become a member to access all 104,069 instructional videos.

get started learn more

If you are already an active lynda.com member, please log in to access the lynda.com library.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Access to lynda.com videos

Your organization has a limited access membership to the lynda.com library that allows access to only a specific, limited selection of courses.

You don't have access to this video.

You're logged in as an account administrator, but your membership is not active.

Contact a Training Solutions Advisor at 1 (888) 335-9632.

How to access this video.

If this course is one of your five classes, then your class currently isn't in session.

If you want to watch this video and it is not part of your class, upgrade your membership for unlimited access to the full library of 2,024 courses anytime, anywhere.

learn more upgrade

You can always watch the free content included in every course.

Questions? Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com.

You don't have access to this video.

You're logged in as an account administrator, but your membership is no longer active. You can still access reports and account information.

To reactivate your account, contact a Training Solutions Advisor at 1 1 (888) 335-9632.

Need help accessing this video?

You can't access this video from your master administrator account.

Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com for help accessing this video.

preview image of new course page

Try our new course pages

Explore our redesigned course pages, and tell us about your experience.

If you want to switch back to the old view, change your site preferences from the my account menu.

Try the new pages No, thanks

site feedback

Thanks for signing up.

We’ll send you a confirmation email shortly.


By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

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.

By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

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

   
submit Lightbox submit clicked