Main

JavaScript DOM Manipulation Mastery: A Comprehensive Guide

The Document Object Model is the glue that brings your HTML, CSS, and JavaScript together, making it possible to develop rich user interfaces for your pages and applications. Learn how to manipulate the DOM in this comprehensive new course with Jeremy McPeak. ► Download unlimited photos, fonts, and templates with Envato Elements: https://elements.envato.com/?utm_campaign=yt_tutsplus_BGkc6dKUZ84&utm_medium=referral&utm_source=youtube.com&utm_content=description If you already understand the basics of JavaScript, it's time to take your skills to the next level. In this course, you'll explore the ins and outs of manipulating the browser DOM in JavaScript. The DOM (Document Object Model) lets you dynamically modify and change the content of your web page in response to user action or other events. Here's what you'll learn in this JavaScript DOM manipulation course: 1 Introduction 1.1 Introduction 00:00:00 Meet your instructor, Jeremy McPeak, and see what you'll learn in this course about how to use JavaScript to manipulate the DOM. 2 DOM Fundamentals 2.1 What Is the DOM? 00:01:16 Before we begin, it's important to briefly go over what the DOM is and how it is structured. 2.2 Getting Elements in the Document 00:10:36 One of the most fundamental things you need to know is how to get elements in the document so that you can work with them. You'll learn about the basic "get" elements in this lesson. 2.3 Querying the Document 00:19:31 The "get" methods are rather limited in functionality. More often than not, the "query" methods are a better option for finding elements in the document. 2.4 Creating and Adding Elements 00:25:53 The DOM gives us the ability to create HTML elements on the fly and add them to the page. You'll learn how to do that in this lesson. 2.5 Removing Elements 00:37:51 If you can add elements, you obviously can remove them. Yep, you'll learn how in this lesson. 2.6 Modifying Element Classes 00:44:13 You've learned how to use the `style` property to change individual CSS properties on an element, but changing CSS classes are typically a better option for manipulating style. You'll learn how in this lesson. 2.7 Working With Attributes 00:54:03 Working with attributes is probably one of the most powerful things the DOM lets us do. You'll learn why and how in this lesson. 2.8 DOM Event Basics 01:04:46 The most important thing the DOM lets us do is react to the user by exposing an event layer. You'll learn the basics of handling events in this lesson. 2.9 Using Event Delegation and the Event Object 01:13:35 You definitely need to understand event delegation in order to write efficient event-handling code. We'll talk about how to do that. 3 Conclusion 3.1 Conclusion 01:24:08 Thank you so much for watching this course. By the end, you have a thorough understanding of how to manipulate the DOM with JavaScript. Here are some useful resources: • Mozilla Development Network: https://developer.mozilla.org • MDN DOM: https://developer.mozilla.org/docs/Web/API/Document_Object_Model • MDN HTML DOM: https://developer.mozilla.org/docs/Web/API/HTML_DOM_API • MDN Event Listing: https://developer.mozilla.org/docs/Web/Events#event_listing Read more about JavaScript DOM manipulation on Envato Tuts+: https://code.tutsplus.com/articles/dom-manipulation--cms-107159?utm_campaign=yt_tutsplus_BGkc6dKUZ84&utm_medium=referral&utm_source=youtube.com&utm_content=description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Envato Tuts+ Discover free how-to tutorials and online courses. Design a logo, create a website, build an app, or learn a new skill: https://tutsplus.com/?utm_campaign=yt_tutsplus_BGkc6dKUZ84&utm_medium=referral&utm_source=youtube.com&utm_content=description Envato Elements All the creative assets you need under one subscription. Customize your project by adding unique photos, fonts, graphics, and themes. ► Download Unlimited Stock Photos, Fonts & Templates with Envato Elements: https://elements.envato.com/?utm_campaign=yt_tutsplus_BGkc6dKUZ84&utm_medium=referral&utm_source=youtube.com&utm_content=description ► Subscribe to Envato Tuts+ on YouTube: https://www.youtube.com/tutsplus ► Follow Envato Tuts+ on Twitter: https://twitter.com/envato ► Follow Envato on Facebook: https://www.facebook.com/envato - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Envato Tuts+

7 months ago

[Music] thank you so you know some HTML CSS and JavaScript and you want to put it all together so that you can create rich and reactive user experiences but you're missing one key component the glue if you will that pulls it all together we call that the document object model or simply Dom and it gives us the ability to manipulate our Pages content with JavaScript I am Jeremy mcpeek within bottle touch plus and I invite you to join me so that I can teach you everything that you need to know to m
anipulate the Dom over the next several lessons you will learn what the Dom is and how it is structured so that you can find the elements that you want to work with add and remove elements to your page on the Fly modify an element style and handle events so that you can react to your users actions by the end of the course you will know what you need to effectively manipulate the Dom but before we begin be sure to like the video and subscribe to the envato touch Plus Channel we have a lot of fant
astic content and I don't want you to miss out on any of it now let's get started [Music] you obviously know that a web page is just HTML at its most basic level and the browser is going to load that HTML and it's going to render it so that our users can view the content that we want them to see but behind the scenes the browser does a lot more than that it loads our HTML into a set of JavaScript objects that we can access and we can make changes to our web page these objects are called the docu
ment object model or simply the Dom and we use JavaScript to access and make changes to the Dom like for example I have a button here that says toggle style when I click it it changes the style of the page if I click it again it goes back to its original state now this change isn't permanent I'm not changing the HTML file here whenever I refresh the page it's going to load from scratch and any change I made is gone but the Dom gives us access to every everything within our HTML so that we can ma
ke whatever change that we want so that we can build expressive and Rich user experiences so the browser is going to build this Dom for us and it's going to be a closely structured to how our HTML is structured like for example there's going to be just an all-encompassing document object which represents the entire document but then there's going to be a property called document element which represents the HTML element there will be one called head that represents the head and then one that rep
resents the body but then we can also access the individual elements or if we wanted to manipulate or make changes to the attributes or even the text of those elements we have that ability so let's go back to the browser let's pull up the developer tools that is the F12 key and let's first of all look at the elements tab now the developer tools are going to be basically the same regardless of what browser you're using primarily because the majority of modern browsers use Chrome as their basis an
d so well it's going to look like this if you're using Firefox the same tools are going to be there it's just going to look a little bit different but this first tab is called elements and it looks like the source code for our HTML but it isn't this is a representation of the HTML as it is currently loaded within the browser and also notice that as I hover my mouse over these individual elements we can see that they are highlighted in the rendered page which is a nice little feature but one thin
g I want you to focus on is this body element right here notice that there is no class attributes or anything like that whenever I click on toggle style the body element changes we now have this class action attribute and it is set to dark now this of course is not in our HTML the body tag has no class attribute whatsoever so what you see inside of the elements tab is a representation of the HTML as it is currently rendered in the document so with the body tag selected let's go to this other pan
el and let's find the properties so remember I said that the Dom is just a set of JavaScript objects so everything inside of the Dom is an object which basically means that those objects are going to have properties and we can see here that with the body selected these are all of the properties that we have access to and there are a lot of them but one thing I want you to notice is that the term node is being used in quite a few places like for example here we have child nodes if we scroll down
a little bit more we'll have node name and node type you will see the term node being used throughout the Dom because everything in the Dom is considered to be a node an element is a node even just plain text is a node and attributes are nodes and with that in mind I want to hop on over to the console here because this is going to give us the ability to access the Dom by just typing stuff into the console so by typing document this is the topmost object that we can use to access and work with th
e document you can see that the browser is highlighting well it did the browser highlights the entire document because the document is what is currently loaded into the browser if we wanted to access the HTML elements we would use the document element property on the document object you can see here that it is still going to highlight that but it's a little bit different than the document and then we can access the head so that is the document.head property since the head really isn't rendered t
hen we don't see that being highlighted but if we take a look at the body we can see that that gives us access to the body but let's say that we wanted to get access to this H1 element now if we take a look at the H1 element that is the first element inside of the body and since it is inside of the body we could essentially say that the H1 element is a child of the body element so there is this concept of children and parents so if we take a look at the body and we just type child we will see a
lot of properties that are listed with child child nodes child children last child first child and all of these other Childs what I am interested in here is this child notes now once again this idea of everything being a node so child nodes are all of the nodes that are children of the body and remember I said that even text can be a node and here we see text as the first child in the body oh that's kind of weird because if we take a look at the HTML there is no text but actually there is it's w
hite space it is a carriage return followed by some white space so it's in between the opening body tag and the H1 element that little bit of text is being loaded in the Dom as a text node and all of these other text nodes are just white space because as you'll notice as I hover my mouse over these individual nodes some of them are being highlighted in the browser and those are primarily these elements the H1 element the P element the div element and the other div element but none of the text be
cause white spaces essentially ignored whenever the browser is rendering our HTML but just because we can't see it does it mean that it is not there so if we wanted to access this H1 elements we could do that using document.body we could use the child nodes now this is a node list which works kind of like an array but it is not an array and since we know that H1 element is the second child inside of the body we would use the index of one and that gives us that H1 element now one thing that I kno
w can be very confusing is the idea of using JavaScript to work with the Dom the Dom itself is not JavaScript they are JavaScript objects but they are not actually part of the JavaScript language so document is not in the JavaScript language but it is part of the Dom and it therefore has a set of properties and methods that we can use JavaScript to access and make changes to body is part of the Dom it's not part of the JavaScript language but we are using JavaScript to program these objects you
can really think of the browser as an operating system we write a program using JavaScript that is going to run inside of the browser now we can access this H1 element in another way there is a first child property which as we know is the text between in the body tag and the H1 element but by accessing that first child we can then move to the H1 element with the next sibling property so we can essentially do what's called Walking the Dom we can walk from one object to another object so that we c
an access yet another object which would then give us the ability to walk to another object it's very tedious very time consuming and really we don't do that anymore instead we have a set of methods that we can use to get or search for certain Elements which we will look at next you now know that the browser loads our HTML into a set of JavaScript objects that we call the Dom and we use JavaScript to access the Dom and we can make changes all we need to do is access the objects that we want to w
ork with like for example if we wanted to work with this H1 element well we could get there by walking the Dom document.body and then we can get the first child which is the text in between the body tag and the H1 element and then we can move to the next sibling and that'll get us there but nobody wants to type that so thankfully the document gives us several methods that we can use to easily get or search for elements the first method is probably the most straightforward it's probably the most
used method and it is called get element by ID and its name basically tells you what it does it is going to get an element based upon 1 that element's ID so here the H1 element just happens to have an ID value and the ID value is supposed to be unique throughout the entire document so this H1 element has an ID of intro text there should not be any other element inside of this same document that has that same ID this is supposed to be unique so we can use this ID to get the H1 element all we have
to do is pass in the ID of the element that we want to retrieve and voila we have our H1 element so let's go back to our HTML let's add a scripts element and let's first of all create a variable H1 element because usually whenever you want to retrieve an element so that you can work with it you want to store it in a variable so that you can easily access it because you don't want to call get element by ID for the same element multiple times because even though it's very fast there is some overh
ead involved because the browser still has to reach into the Dom and find that element so we want the intro text ID that gives us the H1 element and let's say that we wanted to change its text so now that we have this variable this is a global variable and we will have access to it inside of the console here in the browser so let's say that we wanted to change the text so if we take a look at the child nodes we can see that the node list just has a single child and it is that text of the H1 elem
ent we want to change that and if we draw down even more we can see that there is the node value property now I'm pointing all this out because the console is a fantastic tool this gives us the ability to inspect objects to look at what is currently loaded in the browser and what is loaded in memory so that we can get an idea of what is available to us so here we can see that by using this H1 variable that we've created we can use the child nodes on that H1 element so that we can see all of the
child nodes and see their values so we want to change this node value so we can go back to our code here and we can say H1 element and then we could say child nodes and then use the index of zero or we can use simply the first child property either way that's going to give us that child node and then we want to set the node value and let's set it to something like the get methods because we have three methods that we will use to get elements so by making this change we can go back to the browser
we can refresh and we can see that the text for our H1 element changes the get methods now of course we're making this change through JavaScript we haven't made any other change to the HTML so all we have to do is comment out this line of code if we don't want to change change that H1 value and voila we're back to where we were but that's not what we want to do we want to change some of this and let's take this a step further let's also give it a different color now when it comes to changing st
yle which we will talk about later we can do so in two ways we can change the CSS classes that are applied to that element or we can modify what is essentially the style attribute because in HTML we can use a style attribute and then we could set the CSS properties that we want to set well we can do the same thing with JavaScript there is this style property that Maps directly to the style attribute so all we have to do is set the CSS property color in this particular case and we want to give it
the value of yellow so if we go back to the browser this isn't going to be very visible so let's do this let's go to our body let's set the class of dark so that that is going to be default and now we will see that the text of our H1 element is not only changed but it is also yellow well let's change the color of all of the P elements now yes of course we could do this through CSS but where's the fun in that let's do it the JavaScript so we want to find all of the P elements within the document
so that we can change their style as well well the document object gives us a method called get Elements by tag name so basically all we need to do is supply the tag name of the elements that we want to get in this case it is simply p and then that will give us what's called an HTML collection now the child nodes gave us a node list this is called HTML collection which is well it's different than a node list an HTML collection isn't as smart as a node list and we're just going to leave it it at
that but this is also an array like structure so that's we can use the for of loop to iterate over these elements and then we can change their style and we will do that once again by using this style property let's set the color and let's change this to Violet that should be different enough so that whenever we view this in the browser the text changes for our P elements that's great but what if we had elements that had a certain CSS class that we wanted to retrieve so let's add a class to this
first div element and we'll just set this to uh let's just say custom BG and we will give this a custom background so the document object gives us a method called get Elements by class name and it kind of works like document get element by ID in that we pass in the CSS class that we want to search for so in this case we want the custom Dash BG class that is going to give us a collection of those elements and then we can iterate over them using the four of Loop and in this particular case let's
change the background color and we will do that using the style property once again but if you think of the CSS property of background color it is background Dash color well that's not a valid JavaScript variable name so instead whenever you are working with CSS property names in javascripts and it has a dash you simply remove the dash and then camel cases so background Dash color becomes background color where the C is uppercase and in this case we are going to set the color to dim gray that's
still going to be dark but it's not going to be as dark as black so if we go back to the browser we can refresh and there we can see that the background for that first div element is now that gray color the P elements are still Violet and then the H1 element has different text and it is yellow now that's great and all but these methods are very basic we are getting an element by its ID by its tag name or by its class name these methods don't give us the ability to perform any more complex search
es such as retrieving only P elements that are inside of div elements but the document object does give us two methods we can use to perform more complex queries which we will look at next foreign the get element by ID get Elements by tag name and get Elements by class name methods are very useful they allow us to get elements based upon those very specific criteria but they are also very limiting because the criteria is very specific and our documents are much more than just IDs tag names and c
lass names like for example what if we wanted to retrieve only the P elements that were contained inside of div elements now we could kind of do that with using get Elements by tag name but for each individual P element that we work with we would have to essentially walk the Dom we would have to check the parent node of that P element and see if it's tag name was a div and really that's not even enough because remember the idea is to get the P elements that are contained inside of a div element
so we would need to check the parent node of the parent node of the parent node we would have to walk the Dom checking the tag name of each parent node to see if this P element was contained inside of a div and that's just a lot of work that frankly I don't want to do and I know that you don't want to do it either so thankfully we have the ability to query the document using CSS selectors and we can find elements based upon those selectors like for example we want to get all of the P elements th
at are inside of divs so we would use a method called query selector all and then we simply pass in a CSS selector to select those elements so in this case we just want the P elements that are contained inside of a div so that then we could iterate over those elements and let's say that we want to change change the font weight so we can set the style font weight and we will set that to Simply bold let's go to the browser let's refresh and nothing happens let me make sure I saved that file I did
so there's an error somewhere let's pull up the developer tools and the console tells us reference error element is not defined that is correct because in the loop I have let elements that needs to be let element so that should fix that so let's refresh and there we go we can see that those two P elements they are contained inside of divs we can see that those are now bolded the one p element that is not inside of a div is not bolded so great perfect that was an easy way of solving that particul
ar problem but let's say this let's say that we wanted to retrieve this P element right here and this one is inside of a div element as well but we just want that one and let's say that we will set it as underlined so let's call this variable special p and we're going to use a different method it's called query selector so we have query selector which is going to return a single element then we have query selector all which is going to return multiple elements that match the CSS selector so in t
his case we want the P element that is a direct child of div and then we will set the style text decoration to underline so let's go to the browser let's see what this looks like and we see that we have a p element underlined but that is not the P element that we wanted because that is the P element that is a direct child of the div with a class of custom BG that is not this other div element so the reason why this P element was selected was because that was the first element that matched our CS
S selector so whenever you use the query selector method it will return a single element object the first one that matches the selector is going to be returned and that is what you are going to work with so if you want a specific element your selector has to be pretty specific which in our case we can easily do by using the not pseudo class and we want the P that is a direct child of div that is not the P that is a direct child of the div with a class of custom BG and that should work so if we g
o back to the browser we will then see that this other div is now underlined and that is the div element that we wanted to underline to begin with so query selector returns a single element it Returns the first element that matches the selector query selector all returns all of the elements that match the selector so now you might be thinking why would we use the get methods if the query selector methods gives us a more expressive way of finding the elements that we need well that's a very good
question and in most cases I would recommend using the query selector methods because they do offer much more flexibility the exception however is get element by ID so yes we could change this so that we use Query selector and then we could use the ID CSS selector to select that element and whenever we refresh we'll see the same result of course the text change because I changed the text but we still see that that H1 element is colored yellow but if you are going to select an element based upon
its ID it is faster to use get element by ID than it is to use Query selector because there is a little bit of overhead involved when you use Query selector so if you want to select an element based upon the ID and only the ID I recommend using get element by ID otherwise use Query selector or query selector all foreign things that we can do with JavaScript and the Dom is create content on the fly so we can create elements we can give those elements content we can add attributes we can change th
eir style and then we can add those elements to the page now the reason why you might want to do this is you might be working with a web API or some other Dynamic content that isn't automatically loaded within the page but you might want to add it to the page at a later time in this lesson we are going to essentially get rid of everything except this H1 element and in fact let's change the text here so that it is simply manipulating the Dom and we are going to add an ordered list that is going t
o list all of the topics that we have talked about thus far so not only are we going to create the ol elements but we will create the individual Li elements so the first one will be intro to Dom the second one will be getting elements and then the third one will be querying the Dom and then finally creating elements so that's the goal we just need to write the code that is going to do that and to create an element the first thing we have to do is reference the document object because just like u
sing the get methods or the query methods we have to reference the document object it is the gateway to the document itself and we're going to call a method called create element we pass in a string that is the tag name of the element that we want to create so in this case it is an ol element for an ordered list now just by creating this element it is not going to be inside of the document we have to add it to the document and that makes perfect sense because we want to be able to add this eleme
nt wherever we need to and we can do this in several different ways the first and probably the most straightforward is to just simply add it to the end of the document or rather we would add it to the end of the body so every node has a method called append child and then we would pass in the ol element to that method and if we take a look at this in the browser we are going to see the ol element at the end of the body so here's the body the H1 element the script element and the ol element now i
n this particular case it really doesn't matter what order those elements are as long as the H1 element is first I'm happy with that because what matters is how it is rendered in the browser at least in my opinion however we might want to place the ol elements before the script element and we can do that in several different ways the first would be to get the script element object so that we can reference that and then we can say that I want to insert this ol elements before the script element s
o let's look at what that would look like so let's first of all retrieve our script elements we can use Query selector here and we just want to select the script element and once we have that then we would use document body but then we would call a method insert before the idea being that we want to insert the ol element before whatever element we specify so in this case it is going to be the script element so if we take a look at this in the browser we will see now we have H1 is first followed
by o l and then the script element so that's one way of doing it the other way would be to use the H1 element as our reference point and every element object has a method called insert adjacent element and we pass two arguments here the first is a string that is going to specify where we want to insert the element that we pass as the second argument so there are four values here the first is called before begin which is essentially going to insert our elements before the H1 element because we ar
e inserting this before the H1 element begins we can see that by refreshing the ol element is now before the H1 element so we have before begin we have after begin which is going to insert the ol element after the opening H1 tag so let's refresh if we draw drill down into the H1 element we see that the ol element comes before the text of manipulating the Dom the third option is called before end which as you might guess by now this is going to place the ol element before the ending tag of the H1
element so now we have H1 we have our text we have ol then we have the closing tag but in our case I want to use the fourth option which is after end which is going to insert the ol element after the closing tag so now we have our H1 element followed by the ol element and then the script element so as you can see the Dom gives us different ways of essentially doing the same thing which is really a good sign of a well thought out API because no matter what node we have as a reference we should b
e able to insert a another node wherever we need to okay so now that we have this ol elements we need to create the l i elements and we are going to do so using the quote unquote correct way which means that we are going to create an element and then we are also going to create a text node to contain our text and then I will show you an easier way of doing that so we have four Li elements that we need to create so I'm going to call this first one li1 and we will create the l i elements for that
but we also need some content for this so let's create a variable called text and we are going to create a text node and then we pass in the text for this node which in this particular case is going to be intro to Dom so that now we want to add that text to the l i element so I'm going to use the append child we'll pass in text and then we will append this Li element to the ol element just like that so if we take a look at the browser we are going to see um nothing because we have an error that
the ol I got a little lazy here and that is Ol element so if we go back refresh there we see our intro to Dom all right we just have to do that a few more times let's call this text one so that we can have individual text nodes and so now we will create the second Li element and then we will create the text node for that I'm just going to copy and paste we will make the necessary changes and this one was getting elements so that we can append the text to to the li2 so that we can append li2 afte
r li1 so let's test that out and we lost some text probably because I did something wrong and it's right here I overwrote some code I'm not going to fix this because this is a very tedious thing to do we would have to create more elements more text and all of that so instead I think a better option would be to do something like this so that we can have an array of strings and we can just call this array topics and then we would have intro to Dom followed by the getting elements topic then we wou
ld have the querying the Dom topic and then finally the topic of this lesson creating elements so we will use this array and we will iterate over the array to create our elements and then add them to the document so let's get rid of all this other code that we just created and while there are so many different ways that we can iterate over our topics let's just use the for each method and for the call back function we will work with the text so that's inside of this callback function we will cre
ate our Li elements using the create element method then we will set the text now we could create text nodes here but let's just be lazy let's use a property called enter HTML now there used to be some controversy using the inner HTML property first of all because it wasn't standard it was created by Microsoft but the more important thing was that it could mess up the structure of the document but that's not the case anymore this is perfectly fine to do and as its name implies we can use HTML he
re so if we wanted this Li element to have bolded text we could do something like this to where we would wrap our text with a B element and that would be fine so that then we would append this Li l moments to our ol element and that would give us our list so if we take a look at this in the browser we are now going to have our list of topics and we can see that the text is bolded but let's just use Simple Text here we don't need to use any HTML so that now we have just plain ordinary text now th
ere's one other thing that I want to point out to you and that is the order in which I did all of this I created an ol element I then created the LI elements and appended them to the ol element and then finally I added that ol element to the page and the reason why I point this out is because anytime you make a change to the document the browser has to re-render the page so if I created the list and then immediately appended that list to the document that in and of itself would be okay but then
I created list items and appended those list items to the page so every time I add an Li element it would cause the browser to re-render the page now our page is very simple but imagine you have a full-fledged web application a very rich UI and if you make a lot of changes to the UI then the browser is going to have to re-render in order to keep up with those changes so the less change that you can make to the document the better which is why I created the list I populated the list and then I ad
ded the list at the end of this whole process so just keep that in mind now many modern UI Frameworks handle that very gracefully so you don't have to think about that but if you are writing vanilla JavaScript or using some kind of helper Library like JK or something like that then it is something that you will need to be aware of and plan accordingly if we can create and add elements to the document then it kind of goes without saying that we can remove elements from the document and so in this
lesson we will look at removing elements and then in the next lesson we will look at modifying element classes so there we go now of course we don't really care about modifying element classes right now because we are currently talking about removing elements so we don't really need this item this modifying element classes in the list so yo we could fix that by just commenting it out or we could just remove that Li element from our list let's do that that's a little bit more fun so there are tw
o ways that we can remove an element the first involves the parent element so we want to remove this Li element that means that we need to use its parent which is the ordered list element so we would use the ol element and we we have a method called simply remove child and then we just specify the child that we want to remove well in our case it's very easy because the element that we want to move is the last Li element that is in the list so we can use our ol element once again and we have a pr
operty called last child that gets the last child node within ol element so if we go to the browser and refresh we see that that item is now gone that's perfect and one of the really cool things about remove child is that it removes the child but it also returns that child so we could create a variable called the last Li and this gives us the ability to really do whatever we need to with this element now if we don't need to do anything then great it's gone it is no longer in the document but if
we need to make a lot of changes to it then we could definitely do that here or if we needed to move it to another list in fact that would be a little fun let's do that so after our script element let's add a UL element so we want to append it here to the UL element which means that we need to retrieve that so let's call the variable UL element we will use Query selector and we will select the UL element so that after we remove that item from the ordered list we will add it to the unordered list
and we will just use append child now I'll go ahead and tell you that this is not going to work in fact we are going to get an error let's refresh our list is gone so let's go to the console and we see that it cannot read properties of null and it's attempting to read append child and the error is occurring on line 48. so basically it's trying to read a pinned child on a null object so let's go to line 48 which is the last line of code that we executed so it is trying to read append child on UL
element but UL element is currently null so here is one very important thing that you will need to remember and that is you cannot retrieve or work with elements that are not in the document I mean that sounds very obvious but it is something that is very very common now I can hear you saying but it is in the documents it's defined right here after our script and yes it is but here's the thing our JavaScript is executing before the browser has loaded that UL element as far as JavaScript is conc
erned and really as far as the Dom is concerned this UL element doesn't exist because it has not been loaded into the Dom our JavaScript is executing before that happens so a lot of times you would want to place your code at the very bottom of the body this gives the browser the opportunity to load all of the HTML before your code executes it's just good habit to get into so by moving the UL element above our script element well that's going to fix that particular problem so we can go back to th
e browser we can refresh and now we have two lists we have our ordered list and then we have our unordered list that's great so I said that there are two ways that is the first the second way is much more straightforward because we don't have to use the parent if we already have the elements that we want to remove well then we can just call the remove method so this is what we could do we could get that last child let's create the last Li element we will say ol elements so that we could get last
child that gives us that element object so that then we can call the remove method now remove doesn't return anything so if we wanted to continue to work with this last Li object effect then we need to save it as a variable like I did here and so after we save it as a variable we call the remove method that removes it from the document it hasn't deleted it it is just simply in memory out of the document so that once again we can work with it we can do whatever we need to and then if we wanted t
o we can either add it to the same list or we could add it to our unordered list so that's we can go back to the browser let's refresh and we see the same result so three things to take away from this particular lesson first Define all of your JavaScript at the bottom of the document that gives the browser the opportunity to load everything else so that your code can work with whatever elements that it needs to second if you want to remove an element there are two ways the first has you use the
parent element to remove the child that you want to remove the second is to just simply call the remove method on the element that you want to remove there is no right or wrong way to do it just use whichever way makes sense to you one of the most common things that you will do is change an element's style and we have briefly talked about that with the style property that of course Maps directly to the style attribute on the element and then you just simply set whatever CSS property that you nee
d the issue is that if you need to change multiple CSS properties well then you have to write multiple lines of code so here I'm changing the color and then the background color and that requires two lines of code and it's not just more work for you it's also more work for the browser because let's assume that this Li element is already rendered in the page the browser would have to redraw the element with the color red it would then have to redraw the element with a background color of blue and
then of course for every other property that you change it would need to redraw that element so there are times when it makes sense to use the style property there aren't any hard of fast rules for that it just comes down to doesn't make sense for you because more often than not we manipulate Style by changing the CSS classes that are applied to an element that's just what we typically do in modern development but let's first clean up this code a little bit we don't need our UL element we don't
need the code that references UL elements we don't need our script element or at least the code that references that element and let's get rid of practically everything that isn't involved with creating our list and adding that list to the document so that's nice and clean let's go ahead and let's add all of the topics that we will discuss such as working with attributes that will that is what we will talk about next then Dom event Basics and then finally common Dom events so if we take a look
in the browser we should see our list and that's great but what I want to do is color code these so that the topics that we have talked about will be one color the current topic will be another color and then finally the topics we have yet to discuss will be yet another color okay so manipulating the class attribute can be done in two ways the first way is to use a property called class name so our body has a class of dark we can work with that class attribute with the class name property and wh
atever value we set to the class name property is going to be set as the value for the class attribute so by setting class name as an empty string it is going to remove that dark class from the body and now we have that searing light into our eyes so let's change that back but let's say that we want to keep the dark class but we want to add another class like something else but once again this isn't adding something else this is removing the dark class and replacing it with something else and we
can see that being done right there in the browser so what we need to do is get the current value of the class name and we can store that in a variable that I'll just call class name and then we will concatenate that with whatever CSS class that we want to add so then we would set the class name property equal to what is in our class name variable and then our something else class so that now our Dark theme is applied and the something else class is there so this is the first way this is also t
he oldest way and we typically don't use class name at all anymore because we now have a property that makes it so much easier to work with the classes that are applied to an element because this can get not confusing but we can make a lot of mistakes by just using the class name property so instead what we do is use a property called class list this gives us a set of methods that we can use to add classes to remove classes to replace a class with another class or to toggle a class let's start w
ith toggle because that's probably the easiest if the class that we want to toggle is currently applied to the element then it will remove that class so we are going to toggle the dark class which is actually going to remove it because the body element already had the dark class but if we toggle that again it's just going to add it back so that wasn't that useful however I do want to get rid of the dark class because I want to use bootstraps dark theme so I'm going to call the remove method and
we're going to remove the dark class from our body I'm going to do this at the very top of our code so that it is the first thing that we do and in order to turn on bootstrap's Dark theme we have to go to the HTML element and add in the data BS theme attribute set that to dark and now we have a much better Dark theme so we are going to color code our topics so let's start with the color that is going to represent the topics that we have discussed so for our Li elements we will use the class list
property and we will add text info this is a class from bootstrap and it will give us a teal color but of course that's coloring everything and we don't need to do that so in order to know what color to use for which topic we need to keep track of the index that we are working with so thankfully we can easily get the index by specifying the second parameter to our callback function for the for each method it will give us the index to work with we also need to know what the current topic index i
s which I think is five so zero one two three four five yes that is correct so now we can do something like this if the index is less than the current topic index then we will set the class list so that we add the text info class else if index is greater than current topic index we want to add a different class this will be text danger and then finally we have the current Topic in which case we will set the class list to add the text warning class so with that we can go back to the browser and v
oila we have our color-coded topics and that's nice but I want to add a little bit more style to the current topic not only do I want it to be its own color but let's make it underlined let's also make it bold and we can do that by defining a class that has those properties so let's just call the class current topic and we will set but the text underline property or not text underline it's text decoration to underline and then we will set font weight to Simply bold now to add another class all w
e have to do is pass the class name to the add method so you can pass as many classes as you want to the add method and it will add those classes so now whenever we go to the browser we should see our current topic underlined bold and its own color so that's great now if you can add multiple classes it goes without saying that you can remove multiple classes as well all you have to do is pass in the classes that you want to remove as separate arguments so I'm going to add a comment here just so
that we can see that that is something that we can do but after all that let's say that we want to replace the text warning so let's do it like this to where we will call query selector we want to select the element that has the text warning class so that we can access its class list and we want to replace the text warning with text success that will change the color to I think it's green but we'll see let's refresh and we have an error so cannot read properties of null reading class list so let
's take a look here query selector we want to select the element that has Tech o yeah once again that is not inside of the document we need to execute this line of code after we insert that so yeah that that's an issue we can't find an element if it doesn't exist within the document yet so that's an important distinction there so let's go back let's refresh and now we can see that our current topic is a different color because we replaced the warning class with the success class so when you need
to manipulate the style of an element typically the best thing that you can do is modify the classes applied to that element using the class list property you can add you can remove you can replace and you can toggle classes foreign things that we can do with the Dom in JavaScript is work with attributes I know that that doesn't sound very exciting but I guarantee you it is one of the most awesome things that you can do because let's just think about HTML let's look at a div element okay so the
browser encounters a div element and it knows to render it as just a block level element there's nothing else there it's completely boring it's not until we start adding attributes to that element that things start to get a little bit spicier you know we can set classes or we can set the style or there's other attributes that we can set that would change the way that the browser is going to render that element when you start thinking about attributes as a data store a data store that we can use
to Store settings that would change the way that our page behaves well that just opens up the door to whole new set of possibilities like for example the data Dash BS Dash theme attribute that's a mouthful to say I'm just going to say data BS theme this data BS theme is a custom attribute for the bootstrap library and by setting it to dark we have told the browser to use the Dark theme for bootstrap and of course that is why we see the Dark theme if we get rid of the value of dark for that attr
ibute then that changes the behavior in the browser so I want to take this same idea and I want to modify our list so that we will have an actual ol element here inside of our document but then we will have our own custom attribute now whenever you start using custom attributes you want to prepend that with data Dash that signifies that it is a non-standard custom attribute and usually when when you see a attribute that starts with data Dash you want to leave it alone if you did not create it no
w there are some exceptions to that like for example the BS theme attribute that is an attribute that has a specific purpose of setting the behavior of the theme which in this case is dark we're going to do essentially the same thing for our list we'll just call this data Dash theme and then we can set that to multi so that if it is set to multi then we will have our multi-colored list if it's set to anything other than multi then it will be slightly different where all of the topics are one col
or except for the current topic which we need to change the current topic we are now talking about working with attributes okay so let's take this into account we have this ol element we need to change our JavaScript just a little bit instead of creating that element we can use Query selector here to select that ol element and everything should work it does okay so we're good there so now we want to get the value of this data theme attribute because our list is going to be rendered differently b
ased upon that value so let's create a variable to store that attribute value we'll just call it list theme and we will use our ol element object because we have a method called get attribute and its purpose is to get the value of whatever attribute we specify so in this case that is going to be the data Dash theme attribute and that will give us the value so if we go to the browser let's refresh in the console we have that list theme variable we can see well if I type it correctly we can see th
at it is set to multi that came directly from our attribute so we have this value now so that whenever we create these Li elements let's do this if the list theme is equal to multi well then we want to create our list items so that they have those multi-color classes now one thing that we should do here because HTML is not case sensitive we should do list theme to lower case just so that we normalize whatever value is there and compare that to multi so with that in place we should be able to go
to the browser we should refresh and we see everything is just fine however if we change the value of that attribute to something else well then we can see that our list is rather plain but notice here we get an error cannot read properties of no and that is reading the class list oh that is down here where we are attempting to retrieve the element that has the class of text warning uh let's get rid of that because we are going to do this a little bit differently so with that let's refresh and t
hat is great but let's do this let's test to see what happens if we don't have this data theme attribute so let's get rid of that completely let's refresh and now we have an error we cannot read properties of no so what we are getting here is because the get attribute method cannot find an attribute called Data Dash theme it is returning no so really what we need to do here is provide a default value so that if get attribute finds the data theme attribute it will get that value otherwise we will
assign an empty string to list theme and that should make that error go away and that makes our code work so we're good there but let's go back let's add that data theme and really what we might want to do is we might want to make the multi-color theme the default so let's do that that makes a little more sense so that if it is set to multi or if there is no attribute it will be multi-otherwise it will be whatever we set it to doesn't matter what so in that case we get the results that we expec
t effect now the next thing I want to do is add a custom attribute to each individual Li element and to do that we will use the set attribute method to set an attribute we pass two arguments the first is whatever name that we want that attribute to have and then the second is the value we want that attribute to have so I am adding a custom attribute called Data Dash index and I'm setting the value to the index of that particular topic so if we go back and refresh let's take a look at the element
s and let's expand the ol element we can see that now we have the data Dash index attribute and the values are set according to the index of those topics so that's good and now what I want to do is set the current topic based upon the value of the data index attribute that we just created so I'm going to get rid of this else block and here's how we are going to do this the first thing we will do is find the element that has the index of our current topic so let's just call this current topic ele
ment and we will use Query selector to select the l i element that has a data Dash index attribute set to our current topic index that should give us the correct Li element so that we can set the class list to have the text info class and the current topic not text info that was text warning wasn't it so let's do that text warning so now if we refresh there it is we successfully retrieved that element based upon the value of the data index attribute and then we set the appropriate classes so let
's go back to our list and let's change this to multi so that we can make sure that it is working there as well it is so we're good that's awesome now one thing we haven't talked about is removing an attribute and that's very easy to do because we just call a method called remove attribute and there really isn't a good option except for the the bootstrap theme attribute on the HTML so let's do that let's remove that we'll do documents we want the document element and we will remove the attribute
called Data Dash BS Dash theme that will remove that and that will give us the blinding white page let's see what this looks like if we remove the multi value for our list theme it should look fine it does I would say that we should probably use a different color but the the warning text is going to be fine now so far we have been working with custom attributes but you can use the attribute methods on any HTML attribute either custom attributes or standard attributes like for example we can add
a title to the H1 element so let's do that we will use the H1 element object let's call set attribute and we will set the title attribute to um well whatever what is the text they're manipulating the Dom so let's use that but let's also make it a little bit different so that we know we actually set this so this was set in JavaScript so whenever we go back to the browser let's refresh and whenever we hover over the manipulating the Dom then we see the title pop-up that says manipulating the Dom
well that goes away really quick before I can zoom in okay it's not going to let me but you can see that pop-up manipulating the Dom set in JavaScript so it doesn't matter custom attribute standard attribute you can set them you can get them you can remove them the most important thing that you can do using the Dom is set up event handlers now an event is well it's an event it's something that happens within the document most of the time it is initiated by the user doing something such as clicki
ng somewhere or moving the mouse around or selecting some text or maybe even typing it into a form field but there are other events that occur automatically like for example whenever the browser has completely loaded the page not just the HTML and the Dom but also any supporting assets like images CSS and JavaScript there is an event that occurs called the load event and we can write code that will execute when the load event occurs now before we go on let me stress that the topic of events is v
ery complex and we can spend an entire course talking about events in this course we are condensing this into two lessons so this is not going to be in depth but you will learn the fundamentals and the key things that you need to know about events so let's first of all clean things up just a little bit I want to go ahead and use the Dark theme not my theme I want to use bootstrap's dark theme so we will get rid of the code that is going to remove the Dark theme so that's now yeah that looks good
that's a good starting point so this load event we can set up a load event handler by using the window object now the window object is not part of the document object model it is actually part of What's called the browser object model and that key term browser is very important because this means that it is not standard it is part of the browser and the browser object model changes between the differing browsers they have a lot of similarities but they also have some differences but when it com
es to setting up the load event it is all the same and we can do it in two ways the first is to use a property called on load now the event itself is called load that is important but this property is called onload and we assign this property a function that is going to execute so basically unload execute this function that is going to be different whenever we set up an event listener here in a few moments but if we write something to the console we will see some text whenever the browser has lo
aded our page and there we go so what we could do is we could take all of this code for generating this list and we can place it inside of this function that we use for the on load property and whenever we refresh we are going to see the same results that we have gotten before because it's the same code it executes but it executes at a slightly different time when the load even occurs but the really cool thing about this is that now we can move our JavaScript anywhere because it will execute whe
n the browser has loaded the page so if you'll remember a few lessons ago we actually ran into an error when we tried to work with an element that was currently not loaded in the Dom well now that's not an issue because our code will execute after everything has loaded within the the page so I moved the script into the head refresh and we still get the same result so I still think that it's a good idea to put your code at the end of the body but by using the load events you can get away from doi
ng that now there is an issue by using the on load property and that is because it can only hold one value at a time so here I am assigning another value to unload it's another function and so whenever we go to the browser we are going to see that the list is not created but we end up with this message that's written to the console well that's because we assigned a new function to the onload property and so now that is what is going to execute as opposed to what we wrote previously so this can b
e an issue but we can get around that by setting up what's called an event listener we have a method called add event listener to where we Supply the name of the event event that we want to listen for the name is load in our case it is not on load onload was the property the name of the event is load and then we simply specify the function that we want to execute so we can take this function that we have and we could use that as the code that will execute when the load event occurs so let's fix
our onload here and now whenever we go back to the browser we see that our list is there and we can add another event listener for the load event and this one will just add that message back to the console and whenever we run this in the browser we will see both things occurring we will have our list but we will also have our message in the console now I want to add a button so that whenever we click it it will toggle the Dark theme on the page kind of like how it originally was but now we get t
o write that and I I'm going to leave the list code in its own script element in the head I'm going to collapse that just to save a little screen space this way we can keep our code separated and easier to follow along so we need a button first of all and as far as the text is concerned toggle Dark theme and we need to set up an event listener for the click event on that button so we first of all need access to that button element object and it would probably be wise to set an ID let's call it p
age theme toggle button no that's too long a page theme button I think that's going to be okay and then we will retrieve this element using get element by ID and then we will add an event listener for the click event so here we are back into the Dom and we have that add event listener method that is because it actually originated as a method in the Dom and then browser vendors adopted that to set up event listeners for the browser object model so then we just need our function and this is going
to execute whenever we click on that button so let's just test it out briefly it doesn't matter what we write out to the console because we will see it so let's refresh we click on the button and we can see that that is occurring but we are still listening for two load events aren't we so let's clear out that other listener just so that we have one and there we go all right so we need to toggle the Dark theme now that is being set according to this data BS theme attribute in the HTML element so
let's first of all create a variable that is going to store the name of that attribute just so that we don't have to continually type out this entire string because we are human if we have to type the same string multiple times there will be a time when we get it wrong so that is data BS theme and then we want to get the value of that attribute so we will use the document element property and we will call get attribute now we want to normalize this because it could be possible that that attribut
e doesn't exist so if it doesn't we will initialize the attribute value variable as an empty string and then we just need to compare the attribute value to the string of dark if it's dark then we want to remove that attribute so once again we will use document element to remove that attribute otherwise we want to set that attribute to the value of dark and that's all we need to do so let's go back to the browser let's refresh whenever we click on toggle Dark theme we see that it works in this le
sson we are going to change up our plan instead of talking about common Dom events we will discuss the event object and delegation because these are two very important topics that we should talk about and yes common events are important but that is also information that is readily available and in the conclusion we'll talk about some of the places that you can go to get some very good information so here's what I want to do we of course have the ability to click on a button and toggle the pages
theme but I want to be able to click on the individual Li elements and add a background color to them so as we are generating our Li elements we could set up an event listener for each one of those Li elements so we will listen for the click event and then we will execute the code that will give it a background color so the question then is what background color do we use because bootstripe gives us some complementary colors for our text here so we can do this we can set a custom attribute we'll
just call it data color and we will set that to whatever color that we need for that particular Li element so if we have text info then the data color is going to be info in this other case it's danger so we will set that as danger and I guess since we're here let's go ahead and let's add an else and we will go ahead and set up the color for the current topic I know that we did that programmatically by fetching that element and adding the necessary classes but we'll get rid of that that'll also
free up some of our codes to make things nice and clean and that will be just fine so that inside of our click events listener here the first thing we will do is get the color that we need so we have that Li object we will get the attribute which will give us the value of data color and then we just need to toggle that class so we will use our class list to toggle and the class that we want to toggle starts with BG Dash and then the color name followed by subtle so it is a subtle background col
or so with that in place we should be able to go to the browser let's refresh and whenever we click on these items yes we can see that there is a background color if we click on them again we can see that it toggles that background color off so that's great I do want to add the pointer as the cursor on those elements because for the end user whenever they see the pointer they know that they can click on something so we will set the cursor to pointer in the CSS and that looks good so this code wo
rks and that is great however there is a small little issue and that is we have essentially set up identical event listeners they all listen for the click event they all execute the same code the only difference is that it executes that code on different elements and then if you include the click event listener for the button well that's 10 click event listeners and the more event listeners you add to your web page the more the performance degrades now in our particular case it's very simple so
we aren't going to see really any performance issue but as you write larger Pages or as you build web applications that have complex user interfaces that can be a real problem so instead what you would want to do is use what's called event delegation the idea is that we set a click event listener at the topmost level so in our case that's the document and then we check what received the click event and then if it is a button we toggle the theme if it is an Li element we toggle the background so
then the question is how do we go about doing that well it's actually quite simple first of all we set up an event listener on the document so let's start there and since we are handling the click events we are going to add an event listener for the click event so then we need to be able to determine what element received the event and that is given to us through an event object that the browser passes to our function whenever the event occurs so let's do this we will write out to the console th
at event object and a lot of times you'll see that parameter as listed as e sometimes it might be events but there are some issues if you take that approach as well so you might see events I encourage you to use e so let's go to the browser let's refresh and no matter where we click we are going to see an item in the console because we set the click event listener on the document so here we can see that we have a pointer event and we have a pointer event because we used the mouse to click so if
we click pointer event you can see that there are a lot of properties here and one of them is ALT key we can see that it is false if I hold down the ALT key and click again we will see that that is true so that's useful the control key property is also available as well and we are also going to see several coordinates in this case this is the client X and Y that is the position of the mouse in relation to the viewport whenever we clicked if we scroll on down we're going to see layer X and Y then
we will see offset X and Y this is a little bit different so let's clear this out and I'm going to try to click in the top left most corner of the button so we will click that let's scroll down and we will see that the offset X and Y is negative one which sounds kind of weird but whenever you consider padding and borders and margins and things like that you can have a negative one value for a coordinate so the offset X and Y are the coordinates of the mouse when it was clicked in relation to wh
atever element received that event so I clicked on the button and we can show that by going down to the Target property we can see that the target of this click event was the button that has an ID of page theme button so whenever I clicked the offset X and Y coordinates are in relation to the button here and then if we scroll on down a little bit more we can see that the type of event was a click even so there's a ton of information here a lot of it's very useful some of it you will never use an
d there's nothing wrong with that but in our case we want to use this Target because that lets us know what element received the event so let's start by creating a variable called Target and we will set that to the target from our event object and so the first thing we will do is check the ID of the target if it is equal to this page theme button then we know that we need to toggle the documents theme so let's just grab all of that code that we already have let's paste it inside of that if state
ment and we will see that we have the same exact results as we did before we are able to toggle the pages theme so now we need to write the code for whenever we click on one of the LI elements so we can add an else if here and we want to see if the target is an Li element that has a data color attribute and we can do that by using the matches method on our element object we can pass in a CSS selector and this is basically going to return true if the element matches that selector or it'll return
false if it doesn't so our selector is going to be relatively simple we will check to see if it is an Li element that has a data color attribute if it is then we can take the code that we wrote up here let's cut that out let's completely delete the event listener that we defined for each Li element and let's go down to our single click event listener for the document now we do need to make some changes here because we are working with the target as opposed to the LI element but once we make that
change our code is going to work so we can go back to the browser let's refresh whenever we click on any one of these Li elements we can see that the background is either added or removed we can toggle the page theme and everything just works now I know that this can look a little complex and it certainly looks a little string together so one thing we could do is just break this up into different functions so that we can have a function that is simply toggle dark mode to where we have the code
to of course toggle the dark mode that way all we have to do inside of our event listener is call this toggle dark mode function and for the LI elements we could have another function we could call it toggle background the only thing here is that we need to know which Li element that we need to toggle the background on so we could just accept the LI element as an argument we of course need to make the necessary changes once again but then inside of our event listener we can toggle background pas
s in the Target and that is much easier to read and maintain so every time an event occurs the browser is going to pass an event object to the function that handles that event that event object has a ton of information that is relevant to the event that occurred and that is useful whenever you use events which is setting up a single event listener for a particular event and then executing the appropriate code based upon whatever element received the event manipulating the Dom is key for building
Rich expressive user interfaces and it is my hope that by now you feel much more confident in your ability to manipulate the Dom with JavaScript as you continue your journey in web development just remember that learning never stops it is essential to keep your skills sharp and to stay up to date with the latest trends and best practices one fantastic resource is the Mozilla developer Network its webdocs provide extensive documentation on JavaScript the Dom and just about every browser-based te
chnology it is an invaluable resource that all web developers visit but also don't forget us here at tuts plus we have hours upon hours of informational content for web developers of all levels and we are busy cooking up even more content just for you so if you liked this course and found it useful hit the Thumbs Up And subscribe to the envato touch plus Channel thank you so much for watching this course please feel free to contact me through Twitter thetouch plus forums or in the comments if yo
u have any questions from all of us here tuts Plus thank you and I will see you next time foreign

Comments