Document Object Model Series 2023 - Part 3: Manipulating & Traversing the Document Object Model | CM Code_Zone | Skillshare

Playback Speed


1.0x


  • 0.5x
  • 0.75x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 1.75x
  • 2x

Document Object Model Series 2023 - Part 3: Manipulating & Traversing the Document Object Model

teacher avatar CM Code_Zone, !false | funny, because its true

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

    • 1.

      Class Intro - Manipulating the DOM

      1:48

    • 2.

      Moving around the DOM

      2:37

    • 3.

      Building our page

      3:43

    • 4.

      Why do we need to traverse the DOM?

      1:36

    • 5.

      The 3 most important objects

      3:02

    • 6.

      Parent, children and siblings

      4:04

    • 7.

      Parent node

      9:39

    • 8.

      Previous and next siblings

      3:52

    • 9.

      Children, firstChild and lastChild

      4:35

    • 10.

      Children - example

      7:27

    • 11.

      Children and descendants

      2:54

    • 12.

      Children vs childNodes - an example

      5:39

    • 13.

      Challenge - intro

      2:03

    • 14.

      Challenge - solution

      4:40

    • 15.

      Siblings

      0:55

    • 16.

      Siblings - example

      5:23

    • 17.

      Summary

      2:14

    • 18.

      Now it's time to create dynamic elements

      1:18

    • 19.

      Static vs Dynamic sites

      1:46

    • 20.

      Where does createElement() come from?

      2:15

    • 21.

      The difference between Document & document

      5:22

    • 22.

      More on createElement()

      4:34

    • 23.

      Let's add an element to the DOM

      5:00

    • 24.

      Using textContent() to add text to an element

      4:49

    • 25.

      The appendChild() method

      2:11

    • 26.

      The insertBefore() method - example

      2:58

    • 27.

      Is there an insertAfter() method?

      2:23

    • 28.

      Tricking the insertBefore() method

      3:40

    • 29.

      How to remove elements from the DOM

      2:28

    • 30.

      Using parentNode with removeChild

      1:58

    • 31.

      The remove() method

      3:28

    • 32.

      Cloning elements

      2:55

    • 33.

      Cloning - example

      9:05

    • 34.

      Analyzing our clone code

      3:29

    • 35.

      Final Class Challenge - intro

      1:22

    • 36.

      Final Class Challenge - solution

      4:31

    • 37.

      Class Outro

      1:24

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

30

Students

--

Projects

About This Class

WELCOME TO THIS SKILLSHARE SERIES ON THE DOCUMENT OBJECT MODEL. THIS IS THE THIRD CLASS ON THE DOM --> MANIPULATING THE DOM 

What we cover in this particular Skillshare class?

We will cover of ton of information in this entire series, but for Part 3 I'm going to teach you how to (a) traverse the DOM and (b) how to manipulate it by adding and removing items from it. 

Every good developer needs to know how to traverse the DOM—it’s the act of selecting an element from another element.

We know that the DOM is structured as a tree of nodes (in the previous class we discussed nodes, remember), with the document node at the root and every other node (including elements, comments, and text nodes) as the various branches.

Often, you will want to move through the DOM without specifying each and every element beforehand. Learning how to navigate up and down the DOM tree and move from branch to branch is essential to understanding how to work with JavaScript and HTML.

In this class we'll look at some important concepts like:

  • how to move up and down the DOM tree
  • parent, child and sibling node relationships
  • how to create elements and add text dynamically to the DOM
  • how to remove items from the DOM
  • and a BUNCH MORE! 

I can't wait. 

LET'S BEGIN

--- in case you're wondering, here is some more information on the DOM

As you start coding more and more, you will come across the term “Document Object Model” or DOM for short.

As it turns out, the DOM is a pretty important concept in web development. Without it, we wouldn’t be able to dynamically modify HTML pages in the browser.

WHAAAT?

Understanding the DOM will equip you to become an awesome front-end programmer. In fact, it will give you ways to access, change and monitor different elements of an HTML page. The Document Object Model goes further, because it can help you reduce unnecessary increases in script execution time.

In this series on Skillshare, you’ll learn how to implement creative, different and dynamic ideas into your website. Master front-end development and you’re half way to becoming a full stack web developer. Take control through understanding. Delivering an interactive web experience is challenging.

In this series, you’ll be able to answer questions like: How exactly does the browser model your HTML, CSS, and JavaScript? Where can we access this model? What can we do with this model? How can we change this model? By understanding these questions, you will be able to access the DOM and better yet, manipulate it! In other words, you will be able to create dynamic apps that improve user engagement and experience.

What does this entire Skillshare DOM series cover?

This series provides everything you need to start coding dynamic sites by yourself. It gives you the sound fundamentals and practicals regarding the DOM. It can be taken alone to achieve your goals. Rest assured, you’ll emerge from this series with a basic understanding of the DOM and practical experience. We code together, laugh together and sometimes cry together.

This series will take you to the point where you will understand what the DOM is, why we need it, how to access it, where to find it and how to manipulate it. This is awesome knowledge.

In this DOM series, you’ll learn about front-end Web Development, by mastering the Document Object Model.

Why do you need to know about the DOM?

The Document Object Model (DOM) is an essential part of making websites interactive. It is an interface that allows a programming language to manipulate the content, structure, and style of a website. JavaScript is the client-side scripting language that connects to the DOM in an internet browser.

The first step in understanding the DOM is understanding what it is. How does it differ from your HTML markup? How does it differ from JavaScript? From there, you’ll start exploring and experimenting with tools to access the DOM. You’ll learn simple, yet very powerful strategies to access and traverse the DOM. We don’t stop here, but then get into more advanced things like manipulating the DOM (via the create and remove methods given to us by the DOM API).

Knowledge of the DOM is incredibly useful for understanding how your webpage can be improved.

By the end of this DOM series, you'll be able to “speak” DOM by gaining an understanding of where you can find it, how you can access it, and more importantly, how you can manipulate it. We dig deeper in every lecture, learning about things like Nodes, the difference between HTTPCollections vs NodeLists, and a whole bunch more!

Through practical examples, this series helps you understand the DOM piece by piece. And we use the latest and best features of JavaScript and browsers (like the new remove API) along the way so you can stay ahead of your competitors.

*** The most important Web Development course on Skillshare ***

Successful programmers know more than rote learning a few lines of code. They also know the fundamentals of how your browser represents your HTML code and works behind the scenes. If you’re wanting to become a full stack developer, you need to know how to deal with the DOM. You need to know how to access it, how to manipulate it, and how to dynamically interact with it.

I want you to become a successful front-end programming grandmaster.

I want you to be able to apply what your learn in these classes to your webpage.

This entire DOM series is perfect for you.

This series gives you a unique view

Understanding the DOM is a massive topic. To get you up to speed, I’ve spent months thinking about where to focus content and how to deliver it to you in the best possible way.

After taking my DOM classes, you’ll learn "why" things work and not just "how". Understanding the fundamentals of the DOM is important as it will give you infinite possibilities. Armed with this knowledge, you’ll be able to create applications that update the data of the page without needing a refresh. You will be able to create apps that are customizable by the user. You can even allow the user to drag, move, and delete elements.

Can you begin to see how important the DOM is?

How is this Skillshare series different?

There are lots of great Skillshare classes that focus on web development. Pity they never get into the detail about how the Document Object Model works behind the scenes – a skill that every full-stack developer needs to master.

In this DOM series, I focus on true web development in the front end. This includes understanding what nodes are, looking at the Document node (this is different from the document object by the way), understanding the DOM tree structure, what the different types of nodes there are, and how you can use the DOM to access elements on your page and manipulate them.

Practice makes perfect

Theory is abstract and difficult. This is why I love practical examples. We will code together from the very first lecture, right through to the very last class.

Is this class for you?

Yes.

It doesn't matter where you are in your web development journey. It's suitable for all levels.

Still unsure? If you fit in any of these categories then this course is perfect for you:

  • Student #1: You want to dabble in the world of programming. Learning the fundamentals of HTTP, CSS and how you can use JavaScript to change a webpage is the starting point to becoming a full-stack developer.
  • Student #2: You want to know how successful developers build dynamic websites that engage with the user and put them ahead of the competition.
  • Student #3: You want to gain a solid understanding of front-end web development.
  • Student #4: You want to start using backend frameworks like Node.js, but want to first understand how JavaScript is used on the front-end of your webpage.
  • Student #5: You kinda know what the Document Object Model is, but have little knowledge about how it works behind the scenes, and how to practically implement it in applications.
  • Student #6: You have taken other classes in web development but just don’t feel like you’ve grasped front-end development.

WHY START NOW?

Right this second, your competitors are learning how to become better web developers.

Web development is a blazing hot topic at the moment. But you have a distinct advantage. This course offers memorable learning topics, actionable tactics and real-world examples.

See you in the class.

Meet Your Teacher

Teacher Profile Image

CM Code_Zone

!false | funny, because its true

Teacher

Success takes sacrifice.

And sacrifice is something I know a lot about.

I am a self-taught developer so I understand how difficult and daunting it can be for a new comer. 

Today, I continue to code and stay on top of the latest technologies and programming languages. 

It's time to share the knowledge I've gained and to help others succeed. 

See full profile

Level: All Levels

Class Ratings

Expectations Met?
    Exceeded!
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. Class Intro - Manipulating the DOM: Welcome back to yet another class. I'm super, super excited. I could just jump up and down. Thank you for sticking with me. I'm Clyde, I'm going to be your instructor. And this class is a continuation of learning about the DOM, the Document Object Model. And by now you know what the DOM is, you know how to access the DOM. That this class is all about manipulating the DOM. So oftentimes, once you get inside the dome, inside the causal, that's just the starting points. The next step is to move around inside the causal, inside the dome. And in the development industry called traversing the DOM. So I'm gonna be showing you why a node's parents, siblings, children, how to access the DOM and move around within it. It's going to be fascinating and this is very, very important things to know because oftentimes in web apps you want to be able to allow the user to add delete main certain items. So you need to know how to move around inside the DOM, you need to target the correct element. And of course, I'm talking about users creating items on a Wave app. Obviously that means that we have to create an element inside the DOM. So that's what this course is also going to cover. It's going to be IBEC. Trust me, it doesn't matter what level of coding or experience you have. You will learn something new. And don't worry if you're not that comfortable with code that I will be coding along with you. We're going to be doing many examples together. You know me by now. Anyways, enough talk, enough blubber, blubber. I hope to see you in the very first lecture videos. 2. Moving around the DOM: Let's get straight into this awesome topic, traversing the DOM. By traversing, I just mean, how do we move up and down the DOM tree? Will you know how family structures work? You have parents, your parents have children. And if they've got more than one, it means you've got a sibling, eccentric, cetera. Well, as it turns out, in order to understand how to traverse the DOM, and all begins with understanding how family structures work. But of course here we're not talking about literal families. We talking about the DOM tree. That just so happens that our entire HTML page works the same way. How cool is this? And as we saw on the previous section or one of the previous sections, all nodes in the DOM can be expressed as parents, children, and siblings. But what do I mean? Well, let's look at this. Remember that parent, that dude with a beard, a parent of any node, is just the node that's placed immediately above it. And when it comes to traversing the DOM, there are two main methods we can use to get the parent node. The first method is parent node. And the second method we can use this parent element. Don't worry how I use these, all the differences between them just yet. For now, I just want you to take a step back at a high level to understand these concepts. So that's our parent. All good and well, but remember he had two children or what does the child, the child of a node is the node immediately below it. And what's interesting or what do you need to know is that program is often referred to nodes that are beyond one level of nesting as descendants. This is just the terminology you'll hear in the programming world and it makes intuitive sense. So that's your children. But what about if we're looking at children within a family? Well, we know that this is now referred to as siblings. Sibling of a node is any node in the same tree level as that particular node. And what's interesting is that sibling nodes do not have to be of the same time. What I mean, Well, this just means we can have different node types. We can have committed notes, takes nodes, 11 nodes. All of these can be siblings, doesn't have to be at the same time. So there you have it. These are three types of nodes we have in any family DOM tree. We have paranoids, we have children nodes, and we have sibling nodes. It's not that difficult drives how peering Fahrenheit, this is becoming more intuitive. Thus, LET start getting into more detail now. And honest thought coding as well. See you in the next lecture. 3. Building our page: All right. Do you know me? You know how much I love coding and that's why I want us to just jump into it does get cracking. All I want to do now in order to understand how to traverse the DOM, I want to set us up a nice working template, kind of cool it. The base. On the left, I've got my Visual Studio code on the right you can see I've actually got our browser. So you can see the stiffness did progress we make on bullying are simple page. It's going to be very simple, a promising. So it's the base. I just want to create an HTML5 templates. It's cool. I'll title of this document and traverse the DOM because that's exactly what we're doing. I went outside to be very simple. So the first thing is I want to rent out code within a main tag and within this main tag. And when I have an H1 tag that says welcome, they don't want to intrude a div tag beneath that. That's actually have an idea of Rapa. And within this div tag, Let's have an H2 tag with claws of sub, hitting MSH2 tag and just say traversing the DOM. Very simple. Save it. Welcome. Traversing the DOM below the H2, let's have a paragraph tag saying, how do we do it? And below the paragraph tag, we can have another paragraph tag that says, stick around. And I'll show you. And if we save, there we go and updates in our browser. And it's doing this because I'm using Live Server. I've been through this before, but if you do have questions, post them on cunei, explain kind of how that works. So these offers div tag and I'm just laying automotive, take it with me and then we die. And I went to net to be a second wrapper. And within this div tag, Let's just have a joke of the day. So we can even have a class called jerk. And we can say jerk off the day. And the job can be, for example, what do you call fish with no eyes? And answer is fish. And not a very good joke. But this isn't the purpose of this exercise. Cool or ice. Now we've got our basic sites. One I'm wanting to do is quickie guide to the top here and add some CSS very quick under the UCC title, Let's just add a style tag. And yeah, with all elements on our page, Let's start styling. Firstly, I want all elements to have a border. Let's just say if two pixel in width, it can be a solid border and it can be a nice kind of cool it grayish border. So there you go. I've saved as you can see, what that looks like on the screen, doesn't look right, does it? It's gonna get bid up. Now I just want to add some padding to set some padding of 15 pixels on an margin of 15 pixels. Let's see how this looks now. Looking at, I'm looking bid to my hosting a few bit of extra CS. Islam's can make your page look awesome. It's quite cool. And this just style the body. Now we can give it a mix. What if I don't know 600 pixels? We can change the font family. Do they have san-serif, the gut? It looks a bit better. And let's just change a color optics and just space it out a little bit. So here we go. This is our page. How easy was this? I told you I wasn't gonna be difficult. And if we get rid of our code and we just look at our browser, here we go. We've got different elements, different sections, we've got wrappers. And that's why I want to put borders around here. Because I wanted you to see kind of what defines one element from the next. But we're going to be getting into this, don't worry, Kate. I just wanted to code this up with you. I hope you can read along with me and how getting fun, There's just something I want to mention quickly before we move on. This is jump to the other screen. 4. Why do we need to traverse the DOM?: I know we've been through this before, but I just want to quickly re-emphasize US because it's so important. Firstly, the DOM API allows us to do anything to elements and the content. And we usually do this via JavaScript. We know that we first need a way to reach the corresponding DOM node. It's obvious routes in order for us to do anything to it, we need a way to access it. And in the previous sections, we discussed how we can use the DOM API to access certain HTML elements. Yes, we use the ID, the select API, that clause, the tag name. It was fun and there was intuitive and you've actually most of these banana. Although we learned about these access methods, unfortunately it's not quite enough. We need a little bit more. We need the cherry on the top. We've learned that the DOM is structured as a tree of nodes, right? We've seen this. And bearing in mind that the DOM is structured as a tree of nodes. We often want to perform actions on elements, not necessarily according to the ID or class or tag name, but that have relationships to each other. And the key word here, of course, is relationships. To do this, we need a way of moving from one node to another node. In other words, we need a way of traversing the DOM. And that's what this entire section is all about. So sit back, grab a coffee and let's get into it. 5. The 3 most important objects: Before we move on further, There's just something I want to point out to you as to what's most important when dealing with the DOM and you probably already know this. I just want to re-emphasize it because we're going to be getting into a lot more detail and a lot more advanced in the upcoming sections and make just Christie, let's look at the very first two lines of R code. Let me actually just zoom in there if we can you see those two lines will first we've got this doctype, and then we've got this HTML tag, a head. We can take these first two lines and combining it with the King of our entire browser. We can then split this into the three most important things when it comes to the DOM and needs three things on the window object, the document, and the HTML. And we've seen a lot of this before, but if we go to our browser and we access the console, again, let me just zoom in here for you. What we can do is we can do things like this. If we really felt so inclined, we can define a variable called global window object. And we can make that a sign to the value window. And then of course we can access this global window object just like that. And we can open it up and we can see all the window properties. We know this, we've seen, seen it. But it's very weird that we're assigning it to a variable, isn't it? And the same we could do with a document, we could call it adenoid document mode. We could assign that with the venue of document. This is very strange, isn't it? We never do this encoding. And the reason why we don't have to do it is because of our important the window and the document is the DOM provides us with easy access to them via window and document. These are known in the programming industry as global melodies. So it just means we don't have to explicitly declare them, like I have just done. You can just shake it and use it straight out of the container. So we can actually just bright window. And we've got access to the window properties. We can write document and we've got access to the document properties. What about that? Html? Let quite easy to get as well. We can just say that HTML, HTML element. Then we can access our document. Within our document, we put a property called document element, and that is same as our HTML code if we type HTML element now, HTML element. There we go. As our HTML, we've got our head and we bought our body. And if we open up the body, It's literally a law code. So there we go. Just before we move further, I wanted to remind you that the three most important things on the window object, the document, and the HTML element. And these are very easily accessible from the DOM because they're so important. Cool. And I've said, I think you've got the point. Let's move on. 6. Parent, children and siblings: We are cruising through this handhold may seem slow, but trust me, you are going to be an absolute protests. At the end, we've just looked at our doctype and our HTML, the first two lines of code. Now let's start getting further. Once we go below that HTML element level, dom will start to branch out and get very interesting. At this point, we have several ways of navigating around our DOM. One way that we've seen plenty of this is by using querySelector and query selector all to precisely get the elements we are interested in. For many practical cases, these two methods are just too limiting. Why will they can be limiting? Because sometimes we don't know what we are looking for. And as programmers, when you are navigating the DOM, you're going to be finding yourself in this position all the time that you're not quite sure what you're looking for. You don't have a CSS selector. Okay, great. So what do we do? Well, what helps us is this, knowing that all of our elements in the DOM habit least one combination of parents, children, and siblings to rely on. Let's visualize this. We just coded up our HTML. Let's just put on the screen. This should look very familiar. We just did this together. In fact, only thing I added now was I added a comment note. You can see I've edited, this is a comment node. I wanted to just make things a little bit more tricky for us. Let's look at all our code within our body. What can we say about this main tag? Let's draw that again. The main tag is kind of cool it at the very top level. And yes, we're ignoring the actual HTML and the body itself, which starting with this main tag. Below this main tag, we've got three very broad element tags. Don't read H1, the div, and the depth. So far so good. We can even go deeper in the street concrete. We know that we've got the H 2s and the paragraphs, and they are all nested within the dose. So far so good. But now I want us to start looking at the family relationship because this is what's going to help us assess what's going to really put us ahead and our chorea. How does this family relationship work? How does it look like? Well, we know that that main element tag is the parent. What about the H1 and the two div tags? Well, those are the children. And what about below that? What about all this H 2s and the paragraph tags? Well, we can argue day or siblings. So yeah, we have it. We've got the parent we've got the children below the children. We've got a lot of these P's and H2S. We can kind of depends on what we're looking at. But let's just say they're siblings that H2 and the P, For example. Let's take a step at looking at the children. You know, we've got the H1 tag that in a two div tags, we said that those are children will, if we're just looking at them in isolation. We know that they can also be siblings. And why can we say siblings will? Because they shade the main element as the parent. The H1 element has no children, but the div elements, do they have children? The age 20 and p elements of children of the div elements, and all children of the same parents or siblings as well. That's why we call these dyes siblings. But the point I'm trying to make is that just like in real life, the parent the child and sibling relationship is based on way in the tree we are and what are we looking at? Almost every element, depending on the angle with which we looked at under, can play multiple family roles. You yourself may have a child, in which case you'll be the parent. The dual cells may also have a parent being your parents, your mother or father. Hope it's making scenes. I hope you having fun, but don't stop. We only just beginning. Let's jump into the next lecture. 7. Parent node: At this point, you know how important it is for us to move up and down and Dawn, you're getting a scenes of how we read the family tree. It's pretty intuitive. And we're gonna get into now more practical approach. We're going to be looking at what methods we can use to access directly from the DOM API to move up and down the street. So it's super exciting and I hope you're having fun. I've also got this coffee. You can see here a nice, nice, nice, beautiful cup of coffee. Oh, has keeps me going. I don't know why it just something about a cup of coffee, just a ton of pumps me up. So enjoy these niches and let's get into it. Let me just have a quick sip and then we'll get into that promises. And I'm even though it's a little biscuits, become asset is cool. Let's get into it. In order to help us move up and down the DOM tree. Like I mentioned, we have a few DOM API meetings we can use, and you should be able to infer by the names as to what they do. What are some of these methods? We've got fresh outlaws, child pair of nodes, previous sibling nodes, next sibling, hand children. These are the main methods we're going to be using in order to traverse up and down on DOM. And don't worry, don't feel intimidated or overwhelmed. We're going to be getting into each of these in the course. But enough said, LET start seeing what these do. Again, let's pull up our code. This is what we did to get it. Remember, and the starting point is this main tag, that's our wrapper for everything. This is the starting point. Now, for this example here, I want us to ignore that middle div tag. I want us to ignore that ID rep ID. So let's just pretend we don't have it. Only want us to look at the H1 tag and the bottom div tag. And the only reason I'm doing this, as, you know, the page is going to get very messy factors include more and more elements. I just want us to look at these two with NSAID leads, draw it out. What does it look like? We know we've got the body under the body. We put the main, under the main tag, we put the 81 and the div. And within the div with what the H2 and the paragraph element. This is how we can map it out. This is how we can paint the DOM. And the first thing I want us to look at the starting point is with parents. That's right. And as I mentioned, the name itself gives it away and it's pretty intuitive. So let's say we start at the very bottom of our tree, the H2 and the paragraph element. We know that the parent nodes, if we type the method parent node on that H2 element, we going to get returned. What? We're going to get returned its parent being the div element, makes sense, makes sense. And likewise with the next level up, we've got the H1 element, we've got development. They parent nodes or that main element. And of course, we can do exactly the same with Maine or off. Before we go further, I want us to just look at an example of using the parent map. Let's say we'll stuck on the H2 tag. Well, there's currently way we all in our code, how do we access properties on the great grandparent of H2? That is not the parent, not the parent's parent. That the great grandparent body tag, how did we get all the way up the if we sitting on the H2 tag, as it turns out, the answer to this is pretty easy because we are allowed to chain properties and methods together. Let me show you what I mean. Let's jump to the console or write even. Man army was seen that movie. Do you remember also called Ace Ventura as childpid detective. He always is to say All righty then. Hdfs, sir. And how are you this afternoon? All righty then I have a package for you. Anyway. We are here. And the example we want to look at, as we mentioned before, is we sitting at this H2 tag and we want to access the body's property. And for our sake, let's just say we want to change the background color on the entire body to blue. How would we do that? Let's go to our console and start seeing this in action. And you can see here I haven't even touched it since our last example. So let me just clear this console and tidy. And now let's start seeing how the parent node works. Firstly, what I wanna do is if we go to the Elements tab and we look at this body, and we open up our main wrapper. I want to get to our H2 and that's I'm trying to do. He has our H2. So if we click on natural membrane, one of the previous lectures, I told you what that equals, equals dollar sign means. Well, now that we've selected, we can go to our console and we can stop. So let's just say let h, h2 equals dollars there. And again, so if I just console it to the screen, we can see we've got hot joke of the day H2 element. So far. So good. If we are on this element and we access the parent node, remember, what are we going to get? That's right. We're going to get the entire div that wraps this code. Remembered. Hadn't idea of rapid tooth, that's its parent. But I mentioned in the lecture What's really cool about these methods specific, we can chain them because remember we wanting to get all the way to the body element. So let's start working our way. Absolutes exist the parent node, and now we can access its parent node, that div wrapper. What does that give us? Well, that's right, it gives us this main element. If we go to our coding editor, why is that? Well, remember we started at the H2 tag. Its parent is the div. And this div has siblings. Let's go to one that's got the div. These are siblings. It's not its parent. It's parent is this main element of this main tag. And the parents of the main elements, Hayek is the body. As I'm sure you've already guessed at all. We have to do X-Y-Z, what we've just done. You know what? Instead of retyping it out, I'll give you a quick prototype. You can press the up arrow on your keyboard and then just gives you the last code portion that you wrote. And so instead of us writing, and again, we can just click the up arrow. And now we know that this gives us the main element. All we wanting to do is access its parent. And boom, Chaka lacA, we get to this body. How causes. So I just wanted to show you that as how we can actually traverse all the way up our DOM to get to the starting point, which is this body. And before we actually finish off yeah. And change the background color to blue, I just changed my mind. I thought, you know what? I'd like you to try and give it a go by yourself. But this time I want us to start at the first div tag. So if I go back to the coding it into him, I want us to start at this first div tag and a 12 You too quickly now, pause this video. I want you to try and access the body element and change the color, background, color, the whole page to produce these, give it a go, give it a guy. It doesn't matter if you can't get it. That's what I'm yeah, full unit Owens checking on unit and it's not going to impact this course in any way. I just want you to learn and I want you to get full advantage of this course. So pause the video and I'll give it a go. And then in the next few seconds I'm going to show you how to do a school so you can pause it now. Okay, done. I hope you gave it a go. So as I mentioned, I want to start at this div element. Just go back to our console. Let's clear everything out. The first tip is I want us to access the remainder. I said I want to start, date and use we could just type it in our console directly. But I want us to take steps to this approach because as a programmer, we have to be logical. And you'll see it's much easier to logically kids some way in writing one long string of code, unlike seeing that. So how do we do that? So let's say let dv equals what? Well, in this case we know we can use our DOM access methods so we can access our document. Which one are we going to use? That amount? We can use a few. It's got an ID of rapid, doesn't us. So we could use, and I'm just going to use Git elements, get elements by tag name, Nano, the tag name he has div. And as I said, I wanted us to use the very first uptake. Okay, So if a console log analysis, make sure that the right one, and there we go, it is the right end because it's got an ID of Rapa. We could've used get element by ID. There are many ways to skin a cat grain, but what do we wanna do now? Well now we want to access the grandparents and let's define a variable called grandparent. And the grandparent that's going to start at the div. We're going to have to get its parent node. Then we're going to have to get its parent node. So vaccines. So I'm kinda starting at the derivates parent nodes going to be the main element and its parent node is going to be the body. If we return this and with type out the grandparent, they we go, we have the body tag. How cool is us? And yes, let's just do exactly what we needed to do. We access the style property and we change the background color to blue. Glue needs to be in string notation. Sorry. There we go. Whoo, that has brought a friend that has hideous to the eyes. But anyway, I hope you had fun in this lecture, herbicide to feel more intuitive above parent of node. It's fine, right? And it's intuitive. We just worked our way from the very bottom of the DOM tree all the way up. It's not that difficult, appearing finite. We're not quite done. I want to jump back to our previous lines that we want. And I want us to start digging into more of these methods. Siena. 8. Previous and next siblings: I'm having fun. This is where we left off from last time. We looked at the parent node and a hub is becoming more intuitive. So this is parents, this is the parent node. Now I want us to look at siblings, the sibling rivalries. And again, let's start at the very bottom of our DOM tree, the NH2 and the paragraph. We know if we are beginning at the H2 tag, that the next sibling method will return us the paragraph. As I mentioned in the previous later, the words themselves, the method names are so intuitive, like you must know what they're gonna do before I explain it. And if we starting at the paragraph tag and we want to go back to the H2 tag. Yes, the method is called previous sibling. Same if we are one level up in the tree, we starting at one, going to the derivates the next sibling. And of course, if you add a div and you wanna get 81 returned, you can just call the previous sibling method. Awesome. So this is siblings bed again. You know me man, I love looking at practical examples. So let's quickly jump to the console and have a look at how we can use next sibling inaction. See now, I thought this would be a brilliant place for us to just pause quickly and look at how previous sibling works. So what's an example that we can do? Well, let's look at this paragraph tag on here. Okay, if I actually selected we on this paragraph, Let's say we want to access the joke of the day, its sibling, its previous sibling, and we want to change this background color to blue. How would we do that? There's something in here that may surprise you. So let's go to the console. And as we saw in previous lectures, we can just define our paragraph by the currently selected item in our DOM by using the dollar sign 0. Now if we define and we try and access the previous sibling, you can already see in the console that it hasn't returned. That H2 joke of the day that's returned. This takes note, what is up with that? Well, during stress are gonna jump ahead. We're going to be looking in detail into the differences between previous sibling. And if we try and access and other elements, you'll see here this previous element of siblings. Those are two different things, very close, but they are different. And one of the nuances of previous sibling is it also includes all types of nodes, not just element nodes. So if we look at what the text actually is, you can see here that it is a return, it's a character. So if we close it down, the reason that's happening if we go to our console here, this actually return statement after the H2 tag to get to the paragraph. Let me show you that I'm not just talking rubbish. If I delete all characters in between the two tags, that should work. Now, let's go back to our console. Let's refresh. Here. Start again. So let P equals the currently selected item, which we know is the paragraph. And now if we access previous sibling, that should work. Fine wines is not working. He hasn't been defined, sorry. So let's refresh. I actually have to resubmit it. So let's select our paragraph. It's going to the console. Now we can do it. Let p equal $1. And now we can access its previous sibling, same as we did last time, but now we've got no extra spaces or characters in between. We hit Return and day we go with literally got this class of joy and we've got the H2. This is exactly what we wanted. And to prove it to you, we can access it. Change in style, background, color to blue. There you go. Home coastline to make sense if you're unsure, what I just did, They don't worry, we're going to get into it later for now. This is how previous sibling works. See you in the next lecture. 9. Children, firstChild and lastChild: I'm excited and I'm enjoying the stuff. I'd be loving a two. We just looked at sublinks, we saw how those work. We looked at, uh, uh, methods before siblings. Remember what we looked at, we looked at parents, but what is the love of every parent? That is rots. Let's have some kids. Parents love their children. And you may be thinking this is going to be just as easy as the others. And let me warn you, it's not when it starts getting two children. We've got a lot of methods available to us and some of them, like, you know, has intuitive as the others, but it's okay. That's what I'm here for and that's what we're going to look at. Firstly, I want us to begin by looking at the first second child methods. Okay, So how does first second child work? Firstly, the syntax of the method is first child and lost job. And first-child last-child properties refer to parents first and last child elements. Let me show you what I mean. Let's start at that div tag. How does that age to relate to it? Well, as you could guess, that is the first child of the div. If we look at the paragraph tag, as you would suspect, it's the lost child of the div. Again, let's look at it from the main elements point of view. It's first child is a 20 GHz, it's lost child is the div tag. But now what about this body element? Here we can see that the parent, this body only has one child. Willingness case. It's not that difficult. We can deduce that first child and lost child will point to exactly the same element. What about element doesn't have a child? Look at our H1 tag, doesn't have any children, does it? In that case, these properties are going to return null. So first child and lost child will return. Now, at this point you might be thinking, man, this is super simple. Bass. The tricky one compared to the other properties we've looked at so far is the children property. This is just a little bit more tricky, but again, with a bit of practice and a bit of practical examples, you'll see it's not that difficult when you access the children property on a parent, you basically getting a collection of child elements the parent has. Does it make sense? And remember, we looked at the access methods in the DOM when we sold that. Some of those methods like getElementsByClassName, getElementsByTagName, they're turned collections. It's the same here. But as we saw in previous lectures when we used getElementsByTagName, class name, et cetera, et cetera. Although those collections looked like an array, they weren't a true array. So bear that in mind. This load looks and feels like an array. In this case, when we access the children property, it's not a true array. Thus, we can iterate through the collection process or access the Trojan individually, just like we're gonna be seeing in our examples and like we did previously. And if I quickly, the conviction returned to us from this Georgian property does have that automatic links property that tells us how many items are in the collection. And then of course allows us to loop through it. If your head is spinning right now, please, don't worry, we're going to code and we're going to see what this all looks like shortly. So let me just show you kind of other short-run property works. But this time I want to start at the top, looking at the body and we're looking at its children and say we want to access that main element. Or you'd have to do was we will start with the body. We will exist. It's children property. And to get the first item in the collection, just like an array, we access it from its index number. And we know in JavaScript and many other languages and the DOM API, the very first item in the array starts at position 0. So it's not that difficult. What about now if we wanting to get that H1 tag and we add the main element, how would we do that? Again, we start at the main element. We access its children property and we access the first item in that array. It's intuitive. And with the div, we know that that's its second job. So we access the main element, we access its children property, but this time we access the second item in the array, which of course will return us that development. Of course, we can do exactly the same process with the H2 and the P, But this time of reusing the dove as starting point to get the children cope, It's making scenes. But now I really do want to jump into the console. This is an important topic for us to master. I'll see now. 10. Children - example: Working with children is to figure out yes or no. Do you thinking in the real world as well? But, you know, it's, it's the same with the DOM. Children can be difficult, that can be stubborn, and they think they know it all. So anyway, that's what we're going to have to deal with. Yeah. And I want us to spend a bit of time on children. So you'll even see in the next lecture we're going to go into more detail. Yeah, I just want to kind of, you know, I thought let's just skip away from the slides we're just looking at. And let's look here at some practical examples of working with children. So let me just get rid of myself so you can see Beta Adios. And let's look at this body of ours. I want us to actually look at the body element itself. So let's go back to our text editor here. I want to look at this body element and I want to look at its children property. How many children do you think it should have? There might have been a bit of a trick question. It's only got one direct child property, the main element. Okay, So there's got our text editor. And what's really cool while before I start coding here is that the body is directly accessible on the document object itself. So we can just say lean body children be assigned to the document body element and with on net. Remember what one axis we want to access the children, miss it. And remember that returned. That's right. It returns a collection of all its children. So if we hit Return and we console log this out, we get an HTML collection. We really know what an HTMLCollection is. So how cool is this? Or add? This is why we need to learn the basics because everything builds on each other. And we can see this collection is made up of two items. Don't worry about the script. This script is my live server that gets automatically injected by the live server in order for this to run directly from my Visual Studio Code for all practical purposes, we've only got one item in this collection and that is this main element. Remember what I said about the HTMLCollection being kind of like an array will, because it's kind of like an array. We can access the full method and we can actually loop through all the elements in the array. So say we wanted to actually have a red border around the body element. How would we do that? Well, we can just use a simple for loop. So for I equals 0, I less than. Remember how we said that the body Jordan has a length property so we can access it directly. And of course, each iteration we want to increase I. This is very simple. You'll know how to do this. This is just a simple for loop. What do we want to do on each iteration? Will we went to access its child? So this should say the child is assigned to the value of body children. And depending on where we are in the loop, it will return that specific child and always been wanting to do is we wanting to change that style border to, let's just say five pixels, solid gradient. There we go. Let's do that. Does that make sense? So let's hit return. And boom, we've just done it. We've done an awesome job. Yeah. So there we go. We've accessed the body children. We've looped through it. And I know there wasn't much point of looping through because we actually only had one item. The main, I just kinda wanna, I want you to get an intuitive feel for how we can use loops and children and HTMLCollection. Is it making saints bias 100, not quite done. There's one more thing I want to show you now, this was kind of the simple example intuitive one is something else that might be a bit less intuitive, might be a bit of a trick question. What I wanna do is I want us to access our H1 tag. Do you think that the children of the H1 tag? Let's go back to our text data to look at that H1 tag. Sees welcome. Are there any children of that H1 tag will intuitively, you would think not. Remember where the diagram is, no children and you know, you'd expect it to be null for children. Well, let's have a look at our console whether that's the case. Spoiler alert, it's not. But anyway, let's start by accessing this H1 tag. How do we do this? Again, we can use any of our DOM access methods. So we start by accessing the root of our web page being the document on that weekend axis atlas, Dora, of different access methods. I'm just going to use getElementsByTagName again, because we know we've only got one H1 tag in our document. We go we've got our 81. I can even lock it out for you. You can see it's an HTMLCollection and Nissan each one. Great, so we've got the H1 leads now axis its children property. How do we, how would we do that? Well, I want to actually exit the H1 element in an orbit self not this collection. So we accessing the collection now, I want the first item in this collection and then let's access its children property. What would you expect to see? We here we've got an HTMLCollection with nothing in it. And that's intuitive. That's what we would expect, right? We said that doesn't have children. So cool. All is good and well, but what about if we use first child and lost child? What would happen there? You might be thinking out also expected to contain nothing. So let's see, let's see. So we accessing H1, the first item in this collection, and now I want us to access first child. If we return that, we get this welcome takes note was blows your mind. So this H1 tag actually does have a child and the child is the taste itself. It's this welcome taste. And because it only has one child takes child, you would expect it to be the same if we wrote lost child when near yes. And it is the same. And Augustus is the bit that's a bit less intuitive, is that the first child and lost child returns any type of child node, including takes notes that when we access the Trojan property, it only returns us eliminate nodes. Which is why that returned an empty collection versus first-child and lost child, which actually returned us the taste. Don't worry too much about the differences between first child and children. We going to be getting into it in the schools for now to start understanding it. Something else that's interesting is if you only did want the elements does another property. So this axis, our H1 first element in that collection. And instead of typing first-child, we can talk about first element child, which returns intuitively the first element and child of this particular element. And because we know it doesn't have any element children, it's going to return null, which is what we expected and what we saw on the slides previously. We've done a lot and thank you for bearing with me. And I had to sign to understand this stuff. Difficulty. And the more you work with it, the more intuitive it is. I don't want this to intimidate. It shouldn't your mastered this, none of you having fun. And because children are so important, I want us to just discuss children and epic more detail makes some really, really cool and interesting things. 11. Children and descendants: As I mentioned, the children are so important when it comes to working with the DOM that we need to linger on it a bit more. We know that children are just elements that are directly nested below another element. But let's take a step back. And HTML element may have many levels of other elements nested beneath it. And all of these nested elements are called descendants of our starting element. And in our previous examples, we've even seen that there are a whole lot of nice to the elements below, say our body element. But this one special type of descendant and this spatial descendant is an element that's one nice team level below from a given node. And it's called an element. And a child element importantly, can only ever have one parent. We know that all taste in your HTML is also a takes node in the DOM, an x, y. And we sold in kind of peculiar nuanced when we looked at our H1 tag, which we can say is the parent, when we tried to access its first child and lost child, thinking that it was going to return null. We saw that it actually returned takes itself because that takes, is a child, it's a takes note of the one of the parent as it makes sense. The other thing worth mentioning, the SEC, we have a variety of methods available to us that allow us to look at children and children properties. We've seen some of these, but the ones I want to concentrate now on those cold child nodes and children. Let's look at the differences between those methods. Child nodes and children. Let's plop it on our screen here. And let's look at the differences. Firstly, if we use child nodes, it's going to return a node list. And remember we've even gone through node list previously in our natures. How cools at an unordered list can contain any type of node, right? Remember, so we know that accessing dot child nodes returns or node children including text nodes. Whereas if we look at the children property, we know that that returned in HTML collection. We know we can access the dot Jordan method on any element because it's a property of an element. And only garments have this child property. Because of this, we know that these children are all of type element that only contains an element type. And net is the biggest difference between child knows and children in net child nodes returns a node list of any type of node using the children method, on the other hand, will only return an element node. Yep, you guessed us on title theory. Let's jump over to the text editor and I want to go through an example showing you the difference between these two. 12. Children vs childNodes - an example: Right now I want us to pay child nodes versus children Mackay, the one returns a new list, that one returns an HTMLCollection. We've seen this, but let's have a look at this two practical example quickly. So let's take them in. This is our normal code that we did together that we've been doing through this entire section on one test to not add more to this code. Specifically, I want us to add a list. Let's add an unordered list tag within that, let's have three items. Item one, and we'll do another two items, item 2 and item 3. There we go. Let's save this. And let's go to our website. We can see here we've got item 1, 2, and 3. We've just added us. That's clear the console. You can see I'm doing this in real time. By the way, this, this is exactly the code we left off last time. Let me just refresh the page into the console. So here we are a blank canvas. Will firstly, I want to look at this child nodes. Let's have a look at that first. So let's grab our u, our rods are unordered list. How can we do that? Well, in many ways again, I'm just going to use the one we've been using recently and it is getElementsByTagName. Again, the tag name here is the URL. We know we've only got one UL elements within our whole document. So it's going to be an HTMLCollection with one item in it. And I just want to actually exist that item directly. So that's why I'm accessing the first item. And Amy, and that should be our UL tag if we now access child nodes. What do you think that's going to return the link? It's only going to return three items, item 123. No, it's not an it's all points that I'm trying to make. Remainder and child nodes returns a node list, which means it's going to include all the text and carry the brakes and returns in our document. That's why if we open it up, they are actually seven items. So yes, it does have our three LI tags. There's the one, there's the second one, the third one. That in-between we know we've got these returns. So if we open up this text, we can see the node value is a return and it's all the spaces. We go back to our text editor. It's literally the return. And all the spaces. Is it making sense? So the next slide, how would we, for example, loop through all those items and change the background color? Well, let's just put aside the looping for now. What we could do is we could access the first child element, couldn't win. What do I mean by that? Will save me wanted to change the first LI tag to read. What we could do is we start with our unordered list. We can access the first element child. We can then obviously style up that background color and we can make that equal rate, for example. So there we go. That is one way to do it, but this is quite cumbersome, doesn't matter because we can only access one item at a time. Here we access the first element child, not the first child. Remember, the first child also returns kind of every single type of nerd intuiting that takes, That's how we access the first element node. So how can we use a loop? Any ideas? Will, this way we can use children. Remember, I wanted to compare child nodes, which we've looked at. And I want to compare children, children returns and HTMLCollection. And we already know that an HTMLCollection has to only consist of notes. So let's do that. Let's now define you, I'll children as being the URL. Now I want to access the children property. Does it make sense? If we console log this out, we can just confirm before we start coding our for-loop that this returns an HTMLCollection now with only three LI tags. And how we move through this wall, just like a normal for-loop, I wonder, yeah, let me just use this as a template chair for LET I equals 0 body children, but now it's not body children. We've defined our variable as UL children and we know it's got a length property. How do we know it's got a length property? Will I can open this up and show you there's a length property of three. So we know we want to start our loop at 0. We want to keep going until it hits that length of three. And each iteration we obviously want to increase our high by one. Then we want it to actually access each LI tag. And we know the LI tags going to be the list unordered list children and is going to access that specifically and what we're wanting to do now. Okay. We can keep the let's just make it a blue border each. And we hit return. Child is not defined, I sorry. This is x-axis. Again, it's not child, it's alive. That should work now hit return and the rigor we've just looped through each LI tag. How cool is us? I know you might be thinking at this point us in a split, complicated, but extract. Don't worry, we're going to be building the brief practical pages in this course and we're getting more advanced as we go on, you'll see that all of these are pulling on each other. We already know now again with HTMLCollection node lists. We've been through this in a previous section, so you should be familiar with how cool is attached. That's really fun when it's DOS like pulling on each other, we see the practical effects. So anyway, let's keep going. I don't want to stop. See you in the next lecture. 13. Challenge - intro: Do you know what it's time for again? That's right. It's time for a taste. Put your knowledge to the test. I love it. So what I'm gonna do now, some iniquity, give you the taste the question. The next picture, obviously I'm going to go through the example with you, so please try it on your, on your own. Don't worry, they'll be intimidated, should just be fun. And I think you'll get it. I think you, your fonts to math to understand how to do it. So let's cut it up together and it's going to literary and take a few seconds while I'm wanting to do is to create a simple HTML tag. Within a tag, I want us to have an unordered list within our HTML. Obviously, we have to have a body, right? This is good practice within that, I want us to have an unordered list. We can say these are my cool little list items. So the EEG, we can just comment that out. And I just want to have five lists. Will I want? And that can be item one. Right? This can be item two. Item three. Item for an item five, there you go. And this is a tautology. It's only going to take a few seconds. What is your assignment? Will my idea students? I want you to solve two questions for me. The first question is, I want you to count how many element nodes they are. Then beneath that you, Altaic. That's the first question. How many element nodes their growth turn that? This second question is, how many nodes they are in total, not just 11 notes, takes notes, comment nodes, et cetra, et cetra. They are under the UL tag. So they got deja assignment two very simple questions. I want you to give it a go. I want you to think about it. We've learned a lot through this. Pause few sections and dealing with children are very important. That's why I actually wanted to just give you a quick taste. So grab a coffee, get pumped up, try and solve those two questions. It should take you five minutes maximum. And then in the next lecture, I'll show you how we can do it. 14. Challenge - solution: Yes, we did. Awesome. Well, I had to give it a go. You know, I always say the most important thing in these things is to have fun because you feel like you learn better if you actually enjoy what it is you do. So whether you got it right or wrong, lactone executed, the point is you tried and Walden. So here we are. We've got our items on the left and we've got our console on the right. I want us to go through the solution together. But before we do, let me remove myself just because I don't want to get in the way of the console audience. Yeah, we got, the first step is to get our new element, right? And it's just call it a list. We can call it whatever we want. How do we do it? To access this URL as we can access our document, which is our starting point, getElementsByTagName. We know we want the UL element and we know there's only going to be 1 elements that we want. The first item in that HTMLCollection. Boom, we've got our list and I can console log that out just to prove it to you that this is in fact our list. Let's now deal with our first question. Remember what it was. The first question was, I want you to count how many element nodes they are within this list. How can we do that? Do we use the children property or do we use the node list property? That's right, We can use the children property, can't wait because it returns an HTMLCollection of only one type of node, an element node. And how many would you expect to see? And expect to see five, because a five items. So here we go. Let's access our list. And of course, we can access the children that I don't want to return the Jordan, I want to return only the length, right? We needed to count how many can we do that? That's right. We can access the length property and they we go we've got five. Well done, well done. Told you it's not that difficult. Of course, in programming, there are many ways to skin a cat. So another method we can use as we can access our list. And if you start typing, you can even see in our console here, this is straight out of the box. You get given a whole lot of cool that helper methods. It's trying to help us. The very first one on this list is child element count. So we can access that. And as its name implies, a counts how many child elements they are. And this is another way to get to exactly the same thing. As we can see, the logs of these two methods produce the same result, but each does using a different technique. The children property is a read-only property and returns a conviction of the HTML elements inside the element being queried. We then use the length property to get the number of items inside of this collection. Okay. So that's the children property. What about the child element count? Will accessing the child element count me that directly is more intuitive and directly to the point. So in my opinion, it's a lot cleaner. So that is the solution to the first question. What about the second question? Do you remember what that was? The second question was, how many nodes are there within the UL tag? Not just element notes, but how many nodes in general, as I'm sure you've guessed already be we can't use the children property, can we? Because there were two in an HTMLCollection, we need to use what? Child nodes, that's right because that returns a node list. So let's give that a go. And before I give you the solution, actually let me go here to Visual Studio Code. And how many items do you think they should be? Intuitively, how many child nodes do you think they will be for? Well, if you take just the comment and the items, you can see the five items in a comment. So the six basic nodes, but the answer's not six. Remember? We've also got takes notes. We've got a new line and characters before the comment. Here. We've got some off to the comment after each hour I tag. So that means we would expect the six, okay, the starting basic six. Then we would expect 7, 8, 9, 10, 11, 12, 13. Let's see what we get. So if we go back here to our console with access our list, and now we wanting to access the child nodes, child nodes, and we want to access the length property. They're handy, we have it. We've got 13. So I hope this has made sense. I hope you enjoyed this assignment. I think it's quite fun. And also it's teaching you how to use the children and child nodes. And trust me, this is going to be very beneficial for you as a developer. Keep going, stay motivated, grab a coffee, and I'll see you in the next lecture. 15. Siblings: Last but not least, on one us to quickly discuss his siblings. And we know that siblings are just elements that share the same parent. So you can kinda say siblings are like brother and sister. They all located in the same tree level within the DOM. Let me clear something up first. Siblings do not have to be of the same type. Just like your brother or sister is not the same as you, you probably completely different to them. It's the same in the DOM tree. They don't have to be the same time. We also know that nodes higher than a sibling, our ancestors, and those below it are descendants. These are kind of common terminologies used in the programming community. And in case you're wondering, we've seen some of these before. They are a few methods we can use to access the previous siblings and next siblings. Let's have a look at some of these methods in action. 16. Siblings - example: So here we are, we looking at siblings. What I wanna do is I want to access our second, I'll I take the one in the middle and I want to just change that style. And I know this is terrible to use inline styling, but this is such a simple example. I just want to keep it like this. And this changes background color to green. It's now go to our browser. Let's delete the previous example. He has the assignment, we've just done it. Now we can, and the middle item should be green. That's the one we just styled. That's access the console and let's clear the console before we start coding, I just want to emphasize here that sibling properties and methods work very similarly to the children methods we've just seen. In that some methods will traverse only element nodes, whereas other methods will actually traverse every single type of node. Again. So we've been through this before, shouldn't come as a surprise. But the cool thing with siblings is that it's a lot more intuitive, just the word of the method itself. So previous sibling and Nick sibling or return any type of node, any type of sibling. Whereas previous elements sibling or next elements sibling, on the other hand, of course, will return only those elements siblings. So that's about more intuitive in that sense. Firstly, I want to ask you, how did we get to this middle item 2? How would we do that? Because what I'm wanting to do is I'm wanting to change the color of only item 1 and item 3. Novelist, how would we do that? Well, the easiest starting point in my mind would be to access the item to one in the middle. And then all we have to do is change a background color of the previous elements, Sibley, and the next elements of lead. That's kind of how I'm thinking would go about doing this. So the starting point is to exist that middle item to ally, how would we do it? The starting point should be to actually access the unordered list price because then we can start accessing storeroom. So firstly, let's define a variable called URL. What we wanna do is we want to access the getElementsByTagName. We've been through this, you notice is that we know that this is going to return an HTMLCollection, don't we? And we know that I'll whole page a whole document only consists of one, you Altaic. So we want to access the first item in this list. So here we go, Here's our U L, and if we console log that out, I can prove it to you. There it is. Make sense is intuitive so far. But now how do we access the middle item? Well, if you'd thought we could use children, you are a 100 percent correct because the children only contains element items and we can see the three element item. We want to access the second one, right? The one in the middle. So all we have to do is define a variable called middle axis value L exits the children within that UL tag. And we want the very middle item, aka the second item within that collection. So there we go. We console log middle. We've literally got access to it right now in a variable. Also. Now if we want to change that item, one, that background color, to say pink, how we do it? Well remember we've got different methods and it comes to siblings. We've got previous sibling, and we've got previous elements. Sibling. If we just use previous sibling, Let me show you what we get. Previous sibling. The problem with that is that it returns all nodes and it means we actually getting returned to us that text. And in this case, the taste is just to return character with the whole bunches of spaces. That's not what we want, is that we are actually wanting the element itself. So here's one way to do it is to do previous sibling and mimicking exist again, the previous sibling. And then will get us the item we need again. But it's cumbersome. So that's why the DOM API gives us a more intuitive approach to this. And that intuitive approach is accessing the middle variable. And it's just called the previous elements sibling. That's all there is to it. And of course we can access it style property. And we can change the background color to say pink. There we go. We've just changed item 1's background color to pink. What about now atom three? Well, yes. Again, we can access next sibling can predict sibling, as you can see in the console, it's going to return the text node. So yes, we can chain it again, but it's more cumbersome. The easier way is to access our variable and aim to access directly the next element in the sibling method. We can then access that style property, change the background color to say. So today we have it. We've just used Nick sibling, next element, sibling, previous sibling, and previous elements sibling. I hope it's going to make scenes you can see it's quite intuitive. It's not that difficult. So we've seen parents, we've seen children, we've seen siblings. I don't think you realize this, but right now you are actually becoming quite advanced at working in the DOM. And a lot of people don't understand what these methods. So while then I'm super, super impressed, we've done a lot better. We're not quite done. Is lot more lift in this course. 17. Summary: Seriously, seriously, you have done an incredible amount. I am super excited. We've just finished the section on how you can traverse the DOM. And sometimes I think you don't realize how far you've actually come. I mean, right now and you know, if the dome is, you know, how differs from your HTML code. We've been through access methods. So if you know the ID or the cost name of the tag name, you can literary access that specific item straight out of the DOM. But even more than us with just the entire traverse the DOM. Which means even if you don't know what the class name is or the ID, we can move up and down the DOM and change things at our leisure. So Walden and I think like take it in and you've learned an incredible amount already. We've gone through practical examples, we've gone through in theory, we've even done tastes to get at. So like Silverstein, Walden, like keep going, stay motivated. And right now I just want to give a quick recap of what we've learned. And in the next section, all, it's going to blow your mind because now we actually going to start not only moving in the dog and I'm going to stop manipulating it. So you're going to America is going to be. So really, thank you so much, Walden. Thank you. Breathe, relax and enjoy the rest of this very short lecture. And I'll see you in the next section. Audios. We are almost, almost done. This is just a quick conclusion on what we've actually learned in this section about traversing the DOM. We learned how to access nodes. And in doing so, we now know how to walk the DOM tree, as they say in the development community. And this involved as learning about the parent, learning about the children. And of course, between the children, learning how siblings work, you should now be able to confidently access any node in the DOM and don't take this skill for granted at really is important. As I just said, we've still got a ton of information to learn and a long way to go. So sit back, take a breeder, enjoy, and I'll see you in the next section. 18. Now it's time to create dynamic elements: Welcome to this new section on creating elements in the DOM. So it's very cool that right now and you can actually access elements in the DOM. You can traverse up and down the dog. But do you know what's even more Columbus? It's creating new elements in the DOM because my friends, this is what makes week sites and applications tick. We need to create dynamic websites. And to remind you, aesthetic website is kind of us just rotting our HTML and then nothing else happens. Boring, isn't it? Much more exciting to us, is creating dynamic width sizing. And this means we use languages, most commonly JavaScript that we can use others to access and manipulate the DOM which create new elements on the fly. So this is going to be a super exciting section. Trust me, we're going to learn in a readable mom of information. So digital ninja songs, ready, Get ready. Let's learn about how to create elements in the DOM. I'm super, super excited. That's a guide. 19. Static vs Dynamic sites: Okay, so what is next? We've learned to use glosses. Are these tags eccentric, cetera, to find any node in the DOM. And again, don't take this for granted. It's an awesome skill. Rot. Now we can also use parent-child and sibling properties to traverse up and down the dawn. And I'm going to emphasize this again. This is cool. But do you know what's even more cool? Having the ability to create and modify elements in the DOM. So taking a step back, we can say we've got two types of websites, static and dynamic. By static, I just mean elements are added to the page by directly writing code in your index.html file. When ONE boring, lame, plain Jane sacks, you get the points. Static websites, just kinda it anymore. Especially in the world in which we now live. Which brings me on to dynamic websites. This is where elements are added with JavaScript. Oh sweet NAS, the SEC times. You get the points. This is cool. This is what we want in our websites. This is what we actually, you know what, That's not even a 12. That's a need. If you don't have dynamic websites now, you are just going to be left behind the curve, which is y. The first part of these sections in this course we'll all about her access the DOM. But it's not enough because accessing the DOM only gets us halfway. We also need to learn how to dynamically create items in the DOM. So I'm super, super excited in section are really m. I just want to answer a few questions before we move on to actually coding. Specifically, I want to look at how we can create items and also wheat as the method come from, that allows us to do so. Let's have a look at that quickly. 20. Where does createElement() come from?: The most common way to create an element is drumroll element method that's given to us by the DOM API. The question you probably have though, is, where do we find this method will just jump over to the console and have a look. So here we are. I've just opened up a Google Chrome page up there. Nothing to it. I want to find with us create element method comes from. So let's inspect our document as we usually do. You should be very familiar with this banal. And let's go to the console. Let's clear the console and let's start looking for with this method is, you might think, Okay, cool. Let's start by looking within the document. The problem by typing document like this, as we've seen before, is it actually gives us the HTML representation of our document. We don't want that. We want the JavaScript notation or the JSON-like representations to do that, as I'm sure you would remember. We console dirt the document out to the screen. This now gives us a document in JSON like format. And you know what? Let me get rid of myself because I don't want to get in the way here. Now what we can do is we can start looking at this document. If we open up this document and we look at create elements and look at the seas. And you can see it's nowhere to be found. As soon as this happened to you, the next point of coal is to look at its prototype. So if we scroll at the bottom, you see this proto, its prototype is the HTML document. Don't worry, we're going to be getting into all of this later in the course. For now, we're just trying to find it. So let's open up this proton. Is it yeah. Create elements. No, no, it's not. So again, same thing that scroll down to its prototype, which is document. But yeah, it's a capital D. Let's open up this. And does this have creates element? Does this has the create element method. Cooh, that's what all these protons and what is this big D for documents? Let's just jump back to the slides quickly. I want to discuss this in a bit more detail. 21. The difference between Document & document: We've just seen where to find this create element method. Now, this is a really interesting lecture that we're going to go through and it's very advanced. Not many people know how this all fits together. So consider yourself one of the lucky few. I hope you enjoy it and I hope you appreciate it. But it's continuous. So we just saw that we can find this creates element on the document object. And the key thing I want to point out is that it's not the same as the small d. This is a capital D, the document object. So what I wanna do now is I want to compare the document to the document we all use do with the small d. What is the difference and why is the this document what does looked at this? We know we had to start by consoling the document out to the screen. We couldn't just console it directly because that gives us the HTML representation. And we've seen that the proto of this document is the HTML document. All man, what does this mean, this HTML document and why does it have to the day and how does it relate to the document? We'll console log the constructor function of this document. Let's have a look now. We'll wanna do now is I want to see what this constructed that Let's access our window, our document with on the window. And let's access this constructor function, constructor. If we return this, we can see that what's returned to us is this HTML document construct a function. This is very, very important. As we've seen, we can conclude that the document object is constructed from the HTML document constructor. So we can say part of the purpose of this HTML document object is to create that document for us. Maxine's front. It's going to come from some way and that's where it comes from. Okay, great. So now we've got our document that we all used to using. But what is that document will do? Find out we can just console log gets node type. So we exit the window document no time. And as you'll find out it console logs 99 is the code for the document node. We know that the HTML document construct a function creates the document. And we also know it's off type document node. Why is that relevant to us? Because the document is a document node object. We know it inherits from the document node. And yes, it's a capital D is not the same as r small d. This is the big D. And because it inherits from the document and you could almost say that the document node is theoretically the root of the document. But it isn't really the root of the document in all practical purposes. Because the root of our webpage is the first element node in the document, which is the HTML element. Let me show you this right now. Let's just switch to the console cutie or ion. So we can see the kind of at the root of our entire system is this document node. But in all practicality isn't really the root of our document. It should be the HTML document and I'll show you why, Because we want to access the first element within this document node. So in order to do that, let's console. I'll document Archea. And of course, what we can do is we can open up this document. We can then scroll down to its proton, which is the HTML document. We can then scroll down to the document. And I just want to show you here, if we look at the first element child, what's in there? There we go. That's our HTML. This is an all practical purposes, the root of our HTML document. So Rebecca, this is where we left off. We know that the root of our page is in all practical purposes, the HTML element. So we can say that the HTML element is the root or the top-level element of our HTML document. And when this HTML file is loaded in our browser, we know that that constructor function kicks in and it becomes the document object. And document capital D is the ultimate node from which I'll document inherit from PS, both document and the HTML document constructors all instantiated by the browser automatically. When you load an HTML document. This is where they come from in case you're wondering. And typically the use of these methods are associated with providing an HTML document to an iframe. But anyway, that's a bit advanced. But what we've learned in this lecture is incredibly advanced. You now know the difference between the small d document object. Then it ultimately inherits from this big D document node. And then in-between you kinda have this HTML element node and neck kicks in with a constructed to bold the document is 100, can seem a bit confusing, but trust me, it is very advanced and well done for getting this far. I hope you're learning a ton, but don't stop. I'll see you in the next lecture. 22. More on createElement(): Let's get into the meat of creating an element on our page. And that is, I want us to talk about the create element method. All we have to do is we call the create element on our document object. So we access our document using the dot notation. We access the element method. That's simple. And as an argument, all we have to pass as the HTML tag name, aka we have to tell it what element we wanted to create. Make sense. Let me quickly jump to the console and show you how this works. By the end of this section, you're going to be a grandmaster creating elements. I want us to quickly step out of those lines that we were looking at. And I want us to quickly just look at create element. I want you to see how easy and intuitive it is. So here we go. I've got a normal Google Chrome. Open. This, just access the console. C. Here we go. We've got Google Chrome open with the console. Very simple limiter zoom in so you can see the console that better. And let's say we want to add a paragraph to on DOM. How we do that. Well, let's define a new variable called new para. To create an element, we have to access our document object. We know this. We use the dot notation to access all these properties and methods. And the one we want is create element. It's very intuitive. We want to create, of course is a paragraph tag. And then we go, we've actually created a paragraph element. How easy and fun was at. I can show you that we've created it by just console logging out variable out, and here is our paragraph tag. But what might not be that intuitive is, do you think this has been added to the DOM? Or how did we find out? Let's define a new variable called HTML ramada. Define that. We looked at the three most important objects in our DOM, one of which is the HTML. To get that, we just access the document element property on a document. That simple. And if we console log our HTML datas, and if we open up our body, we don't have the pair of Billy. Nowhere to be found in meat. Even make this a bit wider so you can see it. There is no paragraph and this is the point of trying to make and we've created it. That's kind of just in no man's land. Let's quickly jump back to the slides because I want to talk about this in a bit more detail. Awesome. We've just seen how easy it is to create a new element. In particular, a paragraph element. To recap, we created a new variable called new para and net new pair of variable hold a reference tone, newly-created element. We've literally created a new paragraph element. Yeah. Well, not so fast onto your horses. Creating this paragraph element is very quick and easy, but it's just floating around seamlessly in space all by itself. The reason that the paragraph element is lost because that the DOM has no idea it exists. All inclined, what do we do? How do we tell the dominant it exists? In order for this element, this paragraph to be part of the DOM, we need some way to put it. Don't worry. Let me cut to the chess in order for an element to be part of the DOM. The other two things that we need to do. So let's take a step back. We've created our paragraph tag that's floating around aimlessly, and we used to create element method to do so. The two things we need to do to attach it to the DOM. One, we need to find an element that will act as a parent folders paragraph. That's the first thing we need to do. The second thing we need to do is we have to the element we want, in this case the paragraph to a parent element. And we usually do it by using a paint child that paint child method. Does that make sense? So take a step back. The first statement in creating an element is to actually create it. But that's not enough. We need to then define where we want to place it in the DOM. In order to do that, we have to kind of think, Okay, cool, What do we want it to parent to be? And then we need to attach it to the parent. Hope it's making sense, but don't worry if it's not. Because as always, we need to see this in action scene up. 23. Let's add an element to the DOM: Okay, so we've seen that when we use create element, that it kind of floats around in space. And the reason for that is that the DOM has no real knowledge that that element exists. And we also saw that in order for an element to be part of the DOM, the two things we need to do to remember what they were. That's right. The first thing is we had to find which element we wanted to act as the parent. And secondly, once we've done that, we use a method called a pain child to add that element to the parent. Let me show you what I mean. So here we are. I've got Visual Studio Code open and I've got the browse on the right. I really highly encourage you to code along with me because I had more fun. You learn more. So let's get cracking. I just want to create a very simple HTML template here. And yes, we're going to have a head section within the head. We're going to have a title. We can call our title creating elements. And of course we can have a style tag, which we weren't quite do now, but we're going to do shortly. So that's our head. Within our body, I want a very reasonable page and she just wants an H1 tag. And that can be called MI real. We save this and refresh the browser. We can see these are H1. So far so good. Now let's add a paragraph to this. Well, you know what actually, firstly, let's style this quickie. Cool. What kind of styling can we do? Let's just do a simple background color because white is just hideous. So we can change the background color to another. Let's say a nice cool, funky blurry, purply color. There we go. And let's add some padding to this. So these are body. I want us to now style our h1 tag as well because I can't really read that very, very clearly. So let's change the color of our H1 tag to enter one for if, if, if seven. Just so it's more readable, we can actually see it now, let's increase the font size of this. We can change the font family. Let's just put an underline on this taste. So how's that MRL? And now what I want us to do is I want us to add a paragraph to this page. What do we do? Well, let's use JavaScript to do so. So I'm going to include a script at the bottom of this page and needs dot codings and JavaScript. Let's add our paragraph tag to remember how to do that. Well, firstly, let's define a new element. And this new element is going to be a paragraph. Well, our starting point into a whole page is this document object. We exits one of its properties and methods and the one we want is create element. We know this, we've done this before. And the element we want to create is this paragraph. And this is step one. Remember we did this last time we create an element burnouts floating around in space. It's all by itself. How do we then attach this now to the DOM? Easy, we have to first find its parent and then we have to use a pain child. So let's see what that looks like. So call it step 1. Let's grab the parent. And let's just say we want to obtain this paragraph to our body. So of course, let's just define a variable called body element. Of course, document and how we can use a plethora of methods. We've done this before, but I want to use the query selector. And we want to get the body. Let me just make this a little bit bigger. How's it? Sits on one line. There we go. So that's step one. Step two is, let's now attach our paragraph tag to this body. And this is super simple. All we have to do is access our parent, which we define a variable called body element. And we have to access a method on this element called a pained child. This is what I was saying. This is the second part of attaching an item to the DOM. Because now he's saying, Okay, cool, we want to actually attach this pair off to the body. And we've defined our paired off into a variable called new element. If we save this, we have literally done it. If we inspect our document, if we inspect this document and we go to our elements here, we look within the body. They is our paragraph. How awesome is this? So we've literally now edit our paragraph tag to the DOM that the, a few things I want to say about this period of tape because we can't see it on the screen candling, we've added no taste. So how do we do that? Well, let's jump over to the next lecture. I just want to summarize what we've done. And then I want to show you how we add text. 24. Using textContent() to add text to an element: First step, let's represent our code into a DOM tree. How does look like? Well, here we go. We've seen as before, you should be very familiar with it. We started our window, we eventually get to our HTML. It splits out into two branches, the head and the body. These are children of the HTML element, the head as we saw, and he has a title and style, and our body has an H1 tag. And we included that script tag. Didn't really remember within that script tag that when we wrote our JavaScript to add this paragraph to the DOM. So there you go, the exam DOM tree. But what was the next thing we did within our script tag? Remember what that was? Tetrad, we edit this paragraph tag. Let me show you what that looks like. The ego. We literally edit that paragraph tag. Yeah. It's good news rights. We've literally added something to the DOM for our very first time, so well done. And I hope you can see it's quite intuitive and it's not that difficult. But I want us to talk about this paragraph tag and a little bit more detail. As you know, this newly created paragraph elements is not very useful without any taste. In fact, we couldn't see anything displayed on the screen. We only had to inspect the element inspector in order to figure out that a pair of was actually added to the DOM. Third good news though, is that we can add text using the text content property. But how does this takes content properly work hazard look and how do we see it in action? Let me just quickly jump to the text editor and I'll show you now. You know me by now, I love practical examples and we've just said that in order to add takes time element of the hair of elements. In particular, that we can use this property called text content. So let's see how it works. We are in the code that we literally put it up together. And I want to use this takes content property. How do we do it? Well, the first line of code yet within our JavaScript we can see we've created a new variable called new elements. Deck is our paragraph. So if we access this variable, we can access a property called text content. And this is what I want to show you. It's literally this easy and we assign that value of that content we want to add to a page. In this case, what do we want to do? Well, I want to add a paired off and let's just say or a figment of your imagination. And if we save that and boom, we literally have that paragraph in our browser. But that paragraph looks hideous, doesn't have barely read it. So let's just go up into our styles tag here, and let's start styling this paragraph. The game, we can actually use the same calories lost on font-size. We can say out of 36 pixels. We can also change the font family just to be consistent, is actually a bit away to have done all this and put it on top body, which would have helped. But anyway, this is just one of many ways we can do it. And let's just make this bolt font-weight bold. Done. How does that look? So there we go. We've got a paragraph with editor to the DOM and now with also edit text was in a paragraph element. Hopeless. Scientific seems bigger here, console to sweeten CS. And they, we go with a G created our new paragraph that we then access this property called takes content to add content to the page and know, you know this already. Let's jump back into the lecture. Cool, there we go. You can see it wasn't that difficult while Dan, and as I'm shriek is that the combination of create element and this takes content property has created our complete element node. Super, super exciting. But this one question I get asked a lot from students and it is, could we not have used in the HTML instead of that text content? And the answer is yes, you could have used in the HTML. Remember what I keep saying in this course that there are many ways to skin a cat, but they are some disadvantages with using inner HTML. In HTML expresses your site two possible cross-site scripting or XSS. Because inline JavaScript can be added to an element. In other words, takes content is just safer because it strips out the HTML tag. This is quite technical, so don't worry if you don't understand what cross site scripting is a topic of another thing in and of itself. For now, just understand you could have used in HTML. It's just safely to use text content, which is what we've done. I hope you've learned a ton in this lecture. But as always, we have a long way to go See you soon. 25. The appendChild() method: I'd like us to discuss a pained child and Annelida bit more detail before we move on. As we know, using this method attaches your element to a parent. Importantly, though, it always adds the elements to become the lost child of that particular parent. In the example we've just coded together, we saw that our body element already head the H1 and the script elements as children. And that's why when we use the pain child, I'll paragraph tag was added off the R script tag to remember. So you could say that this paragraph is the youngest child in case you for getting mid who was Edit off to the script. Let me just quickly jump to the console and I'll show you. To remind you, here was opcode. We created apparent raphe and then we ended this paragraph to our body element. So let's go to the console. Let's inspect this document. Go to the Elements tab, open up the body and boom, I'll paragraph was added as the lost child will call it the youngest child to a body parent. That is the default behavior of a pain child. So there we go. We've just seen that a pain child and Zao element or pains that element as the youngest child to the parent. Snake animations. You might be thinking at this point, men, do I never have control of way? I want to put this newly created element. The good news is that you do have control. We have multiple methods of adding elements, such as a pain child, which we've seen, insert before and replace child meets. The one I want us to look at now is insert. Before the insert perform method is very simple. One that takes two arguments. The first argument is the element you are wanting to insert into your DOM. In our case, it would be the paragraph tag. The second argument is a reference to the sibling, aka the child of the parent that we want to precede. The bit confused, don't stress the top over to the text editor. And let's look at this insert before method. I'll see you now. 26. The insertBefore() method - example: I hope you having forgotten and this is awesome. That really, really is. And now we're looking at how to use insert before. So remember the default approach and I've got it on the text editor enemy just scroll down a little bit and in zoom in. This is our default approach. Remember we create an element, we then find a parent and then we use a pin child. It's our stick to remember, Let's now touch our payoff to this body by using a pained child. So default approach, but we have no control lean on way. We want that new element placed. So now I want us to kind of tweak this code and I want us to see how insert before works. So in other words, I don't want us to use a paying job. So let me remove that. And I want to say, Yeah, this time, let's use insert before so we can delete that code. And now how does this work? Will the first step in this method is to find the sibling we went to precede. We want to find the spot that we want to insert a paragraph tag into. And let's say we want to insert our paragraph tag off to this H1 tag and a cancer, it's going to be before this script tag. Does that make sense? Currently, we know that our paragraph was added as very, very youngest child, so it was added after the script tag. Anymore, we want it to be before the script tag. So the first step is to say here, let's find the sibling. We want to proceed. In order to do this, let's define a variable called Inequality, anything you want. I'm just going to call it the script element because we know this is the element we want to insert paragraph before. And of course, you know all the access methods by now, we can get the script by accessing a query selector. And we know we are after that script tag. So that's kind of cool. It stick one of two. Now we've got the second statement within state two, and that is using the Insert use the insert before method. How we do this? Remember, I said we find our parent node, which is at body element. We access its property called insert before, which takes two arguments. The one is the new child, which we've defined as new element, which is our paragraph tag. The second argument is the item we want to proceed, in which case, yeah, it's the script element. Here we go. And if we save this, hopefully if all goes well, it should work. So let's open up our websites. You can see our paragraph is still here. Let's inspect the document. Let's open up this body. And they as our paragraph, how cool is that? I hope you are, and that's so awesome because now we've placed our paragraph before they script tag. Very, very cool. Hope you having fun. 27. Is there an insertAfter() method?: Before we move on, I just want to mention a few more things about this insert perform method. Starting point, as always, is to draw out the DOM tree. So here we go, We know this. And the default behavior is that if we use a pain child to the body element, it's going to paint our paragraph as the youngest child. In other words, it's going to paint that paragraph after that script tag. Sometimes as developers, we want more control, don't we? And in our example, we wanted to insert their paragraph before that script tag in between 81 and the script. And how did we do that? That's right. We called insert before on the body element within specified that the new elements, in other words, that paragraph element should be inserted before our script elements. There was that simple and I might be thinking, Okay, cool, That's kind of a weird way because, why should we have to find the latest sibling and inserted before? Surely? Surely they must be an insert often method, as well. As it turns out, is not an insert after method. I don't know why. It's just the way it is. And this means there isn't a widely supported built-in way of inserting an element of an element instead of before. But don't stress, we can trick the browser by combining the insert before method with the next sibling method. What does this mean? Well, it just means what we're doing is we inserting an element before that extra element ahead that we just added? That's a bit confusing. Let me just show you what I mean. So we've got a body, we've got our H1 and we got our script. And assume for now we don't even have text within that hedge one day, we've literally just got an empty H1 tag. In that case, our element is going to be the one and the next sibling of that H1 is going to be that script, right? So all we wanted to do then is we want to insert that paragraph before the H1 next sibling. In other words, before that script element at the stage still might be scratching your head. So let's jump over to the console and I'll show you this in action. 28. Tricking the insertBefore() method: I want us to go back to the basics again. So I've got all code in front of us that are stripped out everything else. And again, if we go back to our browser, we just have MRL. And it's what we have. We haven't got the paired off anymore. Okay, let's go back to Visual Studio Code. Now. I want us to take a step back and think about what it is we want to do. We've got our H1 and we have our script tags, right? And we wanting to add this paragraph before the script tag? Yes, we can use the method insert before. But sometimes your code gets so complicated. Sometimes you want to actually insert something off to something. And like I said, there is no insert off the method, which is why I want us just to go through a quick, quick example. So the first thing I wanna do is I, once I want to grab the body and H1 tag, It's the first thing I want to do. So list define an H1 element variable as our H1 tag. And I'm just going to be using the query selectors. And we know that that's the 81. And of course I can do exactly the same thing. Yeah, But I wanted to find now the body element. And this of course is going to be the body tag. So they would go through really quick. Now I want us to trick the insert before function. Now in order to trick this in super full function, I want to create a new element after the element. And then we've got yet the H1 element. I'll show you what I mean. So I want to define a new variable called H1. That's cool it to the next element. And I want us to access our H1 element. And I want to call emitted. Remember the next element sibling method. We've been through this, you notice it finds the next element siblings. I just want to say, yeah, I could just use next sibling. I don't have to use next elements sibling. I just want to be more co-sharing what I'm doing. Next elements sibling will literally grab the next element. Sibling being that script tag at won't pick up it takes notes. That's the only reason why I did it. Now all I'm wanting to do is I'm wanting to access our body element. I want to use this insert before function. And remember the insert before takes two arguments. The first argument is our new element we want to put into the DOM. And the second argument is that reference sibling, in which case, yeah, we've defined it as H1, next element. How cool is this? Today we go, we have literally done it and I'm going to shoot to the browse and I'll show you that it actually has worked. But just take back and think about why it is we would want to do this. Well, the one major reason I use it as at sometimes you don't always know what that next sibling is in your code. And that's why we treat it with a tree. Grab the current element we on, in this case it's H1 tag. We then access the next sibling method. In our case, we use next elements sibling that we could have used Nick sibling. And then we just treat the insert performance it by using that next elements Sibling we've just created. And then hertz sounds but weird, but trust me, and sometimes you will need to kind of use this car admitted. In order to insert an item where you want it in the DOM. But let me show you it has actually worked. Before we move to the next picture. See how we got this. Just go to the browser. Let's inspect element. Let's go to the elements. It's open up the body and they, we have it. Our paragraph is inserted before that script tag. In other words, that's inserted after the H1 tag. So I hope you learned a lot ARPU finding this fun and intuitive. And I'll see you in the next lecture. 29. How to remove elements from the DOM: You have come in incredible, incredible way. You now know how to create elements and add them to the DOM. And of course, the final step now is to learn how to remove nodes from the DOM. And straight off the bat, I just want to say we have a few methods available to us to remove items from the DOM. The first one I want us to look at is called removes child. Let's have a look at how this works. Welcome back to this tried and tested code. Hope you having fun now who'd be learning a ton? We now know how to create elements and edit to the DOM. Of course, we have to learn now how to remove him. And as I just said, one of the methods available to us as what's known as remove child sets. When I want to look at now, Here we are, we've got our newly created paragraph tag. The first thing I wanna do is I want to add this paragraph elements to the DOM to remember how to do that. Well, first as font, all body elements, we access our document, that querySelector. We grab our body element. And of course we access our body elements. And in this case we're not too fast about way we placed this paragraph tag. So we can just access this append child method. And we can obtain our elements. That simple. If we save this day we go, we've got a paragraph added to the DOM. And I know it seems counter-intuitive, but let's now remove this paragraph from the DOM. And how do we do this? Well, it can't get easier than what I'm just about to show you. All we have to do is we have to access our parent node. In this case, it's the body element. We then have to access one of its methods. And the method we want to access remainder is called remove child. And the child we want to remove is that tracks on newly-created paragraph elements. So we can just remove element. And if I save this, look at that, she gone, she's out of it. We've literally removed an item from the DOM and to prove it to you, let me go down browser, listen, speak this document. Let's make that a bit bigger. And you can see here, this is literally our body tag. If we open that apathy is normal paragraph tag, we've literally removed it from the DOM, so well done. You've just used your first method. And I've told you is not that difficult. That as always, these more than one way to skin a cat. And I want to mention a few more things about this. 30. Using parentNode with removeChild: As I said, I just want to talk a little bit more about this remove child method. The main thing to note is that we have to call remove child from the parent of the child. We want to remove. In other words, this removed child method will not travel up and down our DOM to find the element we want to remove. Now, let's say we don't have direct access to the elements parent, and we don't want to waste time finding it. What can we do? Well, we can still remove that element very easily by using the parent node property. In other words, we just use the parent node property. And in on net property we access the removed child method. Let me show you what I mean. All right, So here we go. Here's our code. Remember we just did this before we use the remove child on a body element. That what if we don't necessarily know what the parent is of the element we want to remove. In other words, we'd actually defined body element with what? If we don't know what that is? Well, in that instance, as I said, we can access the parent node and then remove child on their parent node. How would we do that? As it turns out, it is super simple. We grab our element we want to remove. And it seems kind of weird to start this way. That's what we do within access its parent node property, which will give us its parent. And that parent. Then we say, okay, cool, Then let's remove this element itself. I know it's a bit of a roundabout way, but that's how we have to do it using this approach. If I save this and we refresh our browser, we should see no change. Remember if I comment out this code, we've got our paragraph on the browser. If I take this back in, if I uncommented and we save the reader, that literary does remove that paragraph form our DOM. So hope it's becoming more intuitive. There's one other thing I just want to discuss, cutie. 31. The remove() method: Alright, with bacteria and I'll code, we just looked at CG remove child. Something I have to mention though, because I don't even use removed child that much anymore. And the reason is we put a very thick and a very new way to remove elements from the DOM. And this is provided to us straight out of the box from the DOM API. What is this method? It is super simple, It's just cold remove. So yeah, we got, we've just done an example. Let me show you how the remove function works. And it cannot get more intuitive and simple than this. All we have to do is xy side and we want to remove in this case, well, let me just save this. Then you can sell paragraph is in the browser. I want to remove it now, all we have to do is access our new element. On this element we have straight out of the box and method called remove. And if I save this, boom, it has gone. How easy and intuitive was this? Was? Why don't I start by just telling you what the remove method was in the first place and we can even just forget about the removed child method. Well, I don't know humming the two major reasons I lacked discussing all methods including all the ones. The first one is, it gives you a more intuitive understanding on way we, on how we got to where we are now. So in other words, it just helps us understand our code better. You're going to be coming across old card as well. It has these remove child and you're gonna get like what is that? That's the first reason. The second reason why I didn't mention it at the very beginning is that browsers support the remove method is a very new method. So that means that some of the older browsers will not support it. So if you're wanting to be extra safe, use the remove child method. If you want it to be like me, new agey, you kind of want to understand how the old approaches work, but not really, they stick with the remove method. That's what I use. And trust me, 95 percent of the time, it's absolutely fine. And the remove method, as you just saw, was a lot more intuitive and it allows us to directly access the element and just remove. It hurts really, really simple. But importantly, regardless of the method you choose, both of these methods allow us to remove a DOM element, including ones that were originally in our HTML markup, not just dynamically created once that's important. Another thing worth mentioning is the DOM element we're removing has many children and grandchildren. Those will be removed too. So it is quite a dangerous method that just sort of hit a point that out before you start removing everything and then finding out that literally everything is removed. So there we go. Then you have a Tokyo having a lot of fun. And by the way, if you're wondering what those boxes are, initially, it's Trek us. It's literally Christmas crickets share. I am looking at the 22nd old disabler three days before Christmas, but I just love this stuff and that's laugh general. Maybe do some filming. Me, keep going with my course because when I put this together, you know, and love it, like I really enjoyed hearing signer. Hope your Christmas was good. And I'll see you in the next lecture. 32. Cloning elements: I'm super excited about this section. We're going again to something that we really, really awesome. What, excuse me, a constant because it's really cool. I mean, again, I'm going everyday of a con handle it. What a weirdo. Anyway, I'll try and pick off where we left off. What you're saying was this link is going to be about cloning, about replicating things. That you can start with a unique and one of the kind. So it's going to be super interesting. What about coffee? I hope you do too. And it joins later, sit back, relax and let's get cracking. See anonymous. Woo hoo. This section just keeps getting WIDA. And when the further we get into does not. But fortunately, we pretty much at the last section when it comes to manipulating the DOM, the one remaining DOM manipulation technique we need to be aware of is one that revolves around cloning elements. And by training elements, I just mean creating identical replicas of a certain element. But wow, is this getting weird? It's almost like you're thinking you've got a unique fingerprint. And all of a sudden he defined there's a whole lot of others identically, the same. And that fingerprint, your fingerprint used to be unique. And this is the whole idea about cloning. All right, the inclined wall, how do we clone is pretty easy. We use a method called clone node on the element we wish to replicate or cloning. But hang on to your horses. There's one more thing we need to do. We need to provide this method a true or false argument. And this specifies whether we want to clone just the element, whether we want to clone the element and all of its children. If you're wanting to clone an element as well as all of its children, we pass the value true into this method. If you're just wanting to replicate the element itself at the high level, we pass the argument false. And right now you might be thinking, Cool, understand how it works, but why would we ever want to clone something? Just take a step back and think if there's any scenario in which this some sort of repetition on your website, then cloning would be beneficial. For example, say you've got a dynamic shoppingList And every time a user adds an item to the shoppingList, it gets added to the cart or gets added to a list. That whole LI tag and all styles and the children you have on it. If you do, it'll be awesome if you could just clone it every time the user clicks the Add button, right? Like it make sense, It's actually quite intuitive. But at this point you probably scratching your head. Don't worry, let's jump into the console and let's start coding. Let's start seeing how this method works. I'm super, super excited to see you now. 33. Cloning - example: All right, it's time for a practical example. So you can see in the background I've got code and back into Visual Studio Code. Strip that down. I just have an H 1.5 a paragraph. And if I show you what that looks like if we put our screen here, this is it. Simple, is nothing else to it. It's all I've got what I want to do. Well, let's say we want to replicate this paragraph. In other words, we kind of just want this, right? But I don't know, statically typed it in the HTML. I want this to be added dynamically, and I want us to clone this paragraph. How would we do it? Well, that's what this lecture's about. So let's get into it. Let me just delete these paragraphs. And here we got a late start coding. The first thing I want to do is I want to add a class to this paragraph. And let's call a class message. We can call it whatever we want. And now I want us to add our JavaScript. Now the two things I want to do. Firstly, I want to define where we want to put the paragraph and we want to put it within the body, don't worry. We want it to be a child of the body. So I need an access our body element. The second thing we need to do is I need to define what we want to climb. And in this instance we want to clone the paragraph tag. Hope that makes sense. So the first step is to grab our body element as well as the item we want to clamp, which is the paragraph element. Make sense? So let's define our body element as body element variable. And we can grab this by a number of ways. We've seen as really in the course you should be a mastered this already. The first thing we have to do is as always, access the starting root element of our DOM, which is this document object with our net, we've got a plethora of methods available to us. The 10, 12 years now is the querySelector. And of course we want to get this body element. We're going to do the same thing. But for the paragraph, let's just call it para element. And again, we started the document. Now we can use the query selector. Again, want to mix things up. And that's why I thought I'd put a class there. And as we know, it has a class of message. Today we have a debts. Our very first step, the next thing I want to do is I want to execute a function. And that function is going to add this paragraph tag dynamically to our webpage. If you don't know what functions are, how to write in the syntax demonstrates, I've got an actual whole course on JavaScript and how functions work. If you are interested, you know, give it a go. If not, no stress. I'm going to write a tail with you anyway. All right, so let's start defining our function. Let's define our, and let's call it modern apps say what function qualitative we want. Yeah, we use the function keyword in JavaScript. We then define the name of our function, which is say what? Within the two curly braces, this is where we actually have the meat of our code. The first thing I wanna do is I wanted to find what our clone text is. Let's define a variable called cloned text. And what do we want to clone? That's right, we want to clone our paragraph. Don't we are para element was, unless element we can now access our clone Node method. Remember that in the previous lecture, I'll clone Node method. And do you remember the argument we needed to provide this method? Let's write, we needed to provide a Boolean, either true or false. What do you think we should put here? I want you to think about this. I want you to think whether we need to put true or false into this argument here, into this clone Node. Take a step back. What do we cloning? Cloning that paragraph. And the paragraph is sitting beneath that H1 tag, isn't it? Does the paragraph have any children? It's a bit of a trick question and you might be thinking it doesn't have any children, in which case you should put false. But that would be wrong. That I'll show you in the next day to y for now. It does have children. It's actually got that takes node as a child. So we have to pass in the argument true. So there we go. At this point in time, we literally have cloned our text awesome rights bit. Similarly to when we use the create element method. Remember how it just floats around in sunny all by itself seamlessly. All the same thing is going to happen here. We've created this clone taste element, this paragraph. Then it's just floating around. We have to attach it to a parent. And that's exactly why we had to create that body element. You need to scroll down a bit so you can see, there we go. So all we have to do now is we have to access our body element. We have today news, the append child method where we don't have to just what we're gonna do here. And of course, the argument or the child we want to append is our cloned text. Doesn't make sense. But at this point in time, if we just stop here and we go to the browser, nothing was happening for us and we can inspect the document. And we can open our body. And you can see we've only got one paragraph. There is no second paragraph. We haven't done anything. In other words, we haven't executed dysfunction. We've created the function, but we haven't executed at it. And how do I want to do that? Or we could just execute the function by cooling, say water over here. We can go back to our browser, and there we go. We've literally added a paragraph to our DOM alkalosis. But I want to do it dynamically and I wanted to keep happening every 1 second. So how would we do that? Let's go back here to our code. And I want to use now a DOM inbuilt method called sic interval. So here let's use a bolt in DOM function, which by the way is from the window object. To execute our say, what function every 1 second. And the method I want to use is called sit interval. And just a bit of a fly, a lot of people, and if you start googling sit interval, they think it's a JavaScript method. It's not a JavaScript method. It comes from the window object within our DOM again. So here's just a bit of information for you that you can put out at the next party era. Sit interval method takes two arguments. The first argument it takes is the handler. In other words, it's the function you want to execute. We want to execute the, say what function, don't we? The second argument is how often we want this function to execute the timeout. Yeah, we want to execute this function every 100 milliseconds, in other words, every 1 second. Now if I save this and we go to our browser, look what's going to happen. Yeah, it makes you just shut this down. Let me refresh. Look what's happening. A hub that is blowing your mind. How cool is that? And if we inspect out elements on our page and we open up this body is just refreshes, pair to it and start again. With us. Look at their paragraph being added to our DOM. Dynamically. Whoo, That is awesome as an adult man, hope years Hampton excited as I am literally manipulating the DOM on the fly. It's automatic, baffles my mind. I think it's awesome. Something I want to show you that quickly is if we go back to our code, if we run the head false as our argument here, what do you think would happen? Do you think the paragraph would be added to the DOM? You might have said no, but actually the paragraph is still edit to the DOM. But without any Jordan intuiting, it's TXT children. It takes none, it is economic sense. So if we go back to our page now, you can see that our page itself is not being updated because there is no text within the paragraph. But if we inspect this document and let me refresh. You can see in your console, in your DOM that paragraph is being edited every 1 second. Hope it makes sense that in the next lecture, I want to look at this code in more detail and just summarize what we've done. 34. Analyzing our clone code: I want us to just take a step back and understand what it is we just done because it's such a cool and interesting topic does and nominee other tutorials that are found on courses. If a covered this kinda stuff. So I hope you appreciated her burning fun. But anyway, the secret to what's going on yeah, lies in our code. Let's actually get better occurred. And specifically we don't need to talk about the H1 and the paragraph does a pretty straightforward. What we need to do is we need to jump back into our script tag. And we need to take a moment to understand what's going on. At the top, we have our body element variable. The first thing we do is we define our body element variable. And that references the body element in our HTML. Pretty straightforward. In similarly, we define our parent element variable and then references our paragraph element with a class value of message is nothing too special going on here, you should be very familiar with this. Now, here's where things get interesting and funky. We have our set interval timer function that calls the say what function every 100 milliseconds, every 1 second. It's inside this, say what function where the actual cloning is taking place. So you could say the most important part of code for us is this. Say what function? How does this work? Will again, we define a variable called cloned text. And we assign that the value of our cloned eliminated. In order to clone an element. All we did was we used the clone Node method on our paragraph element. The result of us doing this is that a copy of our paragraph element is now created and stored as part of the cloned text variable. The last step is for us to add our newly turned in momentum to the dorms so that it shows up. Remember, without doing this, it's just floating around in the name, it's lost. We need to attach it to a parent. Does make sense. And that's why we access element the parent. We then use that paint child method, which we've seen in earlier lectures. And of course we add the cloned text to this body element. And thanks to our set interval, all of the code under the say what function repeats to keep adding are cloned element to the page. And of course, the final thing that you noticed was we passed the value true or false. Yaks, it's the last example we showed, but we did actually pause true as the argument into this clone Node function. Why did we do that? Our paragraph element doesn't seem to have any children, right? Well, this is where the distinction between elements and nodes comes into play. Our paragraph tag doesn't have any child or elements that the text within the paragraph tag is actually a child node. Specifically, a child takes node. And this detail is very important to keep in mind when you're finding a soft cloning something and not expecting to see what you did. I hope this is making scenes. A hub is coming more intuitive to you by now. And most of all, I hope you're having fun. 35. Final Class Challenge - intro: I thought it would be fun just to have another exercise to apply what you've learned. You can see here in the background, I've got a very simple page called cool animals. And under that, I've got a whole lot of list items. And what I want you to do is I want you to think about how you can dynamically add these list items to the page as I've done. So I'll show you the code and are provided in the lecture. You can download a novel. But this is the starting point. You can see just at a very simple CSS. And if we scroll down, this is where the crux of the exercise comes into play. I've got an 81 and a UL tag. Pretty straightforward. Then I've got R script, I've got our JavaScript, Find an array called animals. That's what I've done. What I want you to do is I want you to add all these items within that UL tag dynamically. With JavaScript. Can you figure out how to do it? You know how to access the DOM, you know how to create elements, you know how to put those elements into the DOM, give it a diode. And in the next lecture, I'll show you how I did it. It really isn't that difficult, but it should just reinforce or deflect, have yes. 36. Final Class Challenge - solution: Did you give it a go? I hope so. And you'll see here how intuitive and easy it actually is once you understand all these methods, it's really fun. So let's get into it. What's the first thing we need to do? Well, let's try it. We need to define where we want to put this LI tag that we're going to create into. Remember we put attached to it apparent, in that case our parent is the alt tag. So the first step is let's define a URL. Let's call it UL element. And we can literally find it. We can assign it a value. Yes, we started to document. This is the root of our page. We access a method called querySelector and we just find the UL tag. There, we have it. This is the first step. The second step we need to do is we need to create an LI tag. We need to then add takes to that LI tag, and then we need to edit to this new element. How are we going to do that? Well, firstly, we've got an array called animals. We need to kind of loop through that array. We need to then grab each item that we're looping through. Include that as the takes to the LI tag and then we add that to the URL. I hope that makes sense. Let me show you how our dirt. Again, there are many ways to skin a cat when, I mean, we could use the traditional for-loop, I want to use the four of us just more intuitive to me. If you don't know what that means. Again, you can do my JavaScript course. You can just Google it. It's very simple for loop. So yeah, all I'm wanting to do is I'm wanting to define a for of loop. Iterator is each item in the array. And we're just going to call that animal. We can call it whatever we want of what object while we wanted to loop through that array called animals. So there we go. Each time it iterates through this array, it's going to throw us back that animal name in a variable called animal. That's all it does code means and all that it's doing. Please don't be intimidated. Tsunami. Know that each time it loops through this array, we're going to have that animal name in a variable called animal cool. That's cool. But what's the first step? The first step is let's create our list item. Let's just call it list item. How do we create this? Remember we started our document. We access a method called create method. Create element, sorry. And the element we want to create is this Allied attack. So far so good, right now you'd agree with me that we've created an ally tag, but it's empty. There is no taste. And in one of the previous lectures, much, much earlier, we did discuss how to add text to a newly created element. Do you remember how we did that? Let's write we access a property on the element called text content. We could use in HTML. But for cross-site scripting attacks, it's much safer to use takes to content. So let's do that. Let's access our newly created list item. We then want to change its takes content, don't we? And what do we want that to be equal to? What do we want to assign that to? Where we want it to be the name of animal. And as I mentioned, we've got this variable called animal to each loop iteration. So there we go. We've literally now or manipulated it, takes content. What's the last step? The last step is to add this to our DOM, right? Novice is floating around in space all by itself. We have to edit to something. Yeah, we define the UL element as its parent. We want to access the pain child method, NGS. We went to paint what we want to append this list item. So there we have it. Before I save, if I go to the browser, you can see here we've just got a heading called cool animals. I'll go back to the Visual Studio code here and I save. What do you think's going to happen on? Well, I hope it worked. Let's go here to our browser. And boom, the IGA, this is awesome. We literally have what we were wanting. Hope it does making sense. I hope you had fun with this exercise. This really has put a lot of the different concepts you've learned in the course together in creating something really cool and fun. While that, I'm very, very impressed. 37. Class Outro: Speaker that you've got a seller, right? Literally just finished a massive class. Talking about manipulating the dominant way, moving around with adding dynamic HTML elements to it. Come on, this has gotta be exciting Walden seriously, you've learned about nodes. You learned that in the development industry we kind of look at nodes as a parent, child, sibling relationship. And once you grasp that, it really isn't that difficult, it's quite intuitive to traverse the DOM Walden seriously, pat yourself on the back and don't take for granted how much you've learned up until now. But but for me it's always a bat, isn't there. We're not quite done. Because in the upcoming classes, in fact, in the very next loss, we're going to now be talking about a crucial concept in the DOM and that is events. Because oftentimes you don't just want to create something statically. You want to react to certain events when a user clicks a button or a vein, do you want to do something when you use a scrolls with the mouse, when a user executes a key up event, only then do you often want to do something. So with that said, let's take a break, get a coffee. And in the next lecture, Let's start talking about dormi veins are called white.