Modern JavaScript Tutorial #6 - The Document Object Model

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
alright then gang so I think we've reached a point in the course now where we've nailed all of the JavaScript basics and we can start to do things which i think are a lot more fun like interact with a browser or a web page and we can do things like add content to a web page with javascript or we could change the style of a web page with JavaScript or we could do things like react to use events like click events when they click on a button and we can also do things like create an annoying pop-up and I'm going to show you how to do that as well because at the end of the day this is the kind of thing that JavaScript was initially created for to make a webpage and it uses experience on a web page more interactive so we'll be kicking off this chapter by learning first of all about the document object model this is going to be the mothership of this chapter and everything we do to interact with the browser is going to be governed by the document object model also known as the Dom for short then we're going to look at how we can add change and remove content from a web page we're also going to talk about use events like click events or Mouse movie events and see how we can react to those in JavaScript and finally we'll put everything together that we learn to make a nice little popup effect on a web page now for this chapter and pretty much everything going forward you need to make sure you have your web server still running so we can preview what to do in the browser now in one of the first chapters in vs code I showed you this packaged live server and I showed you how to spin up a local development server using that so we can preview our web pages in it but just in case you've forgotten I'm going to show you again now so remember first of all you need the live server package installed so you need to search for that there if you've not got it already then come to the HTML page that you want to open with the live server right click and go to open with live server and that is going to open it up in a browser so you can preview it so you need to make sure you're running your page on a live server for the rest of this chapter and pretty much the rest of the course so they're my friends the document object model or the Dom for short it's at the heart of any kind of web page manipulation but what exactly is it well it's something created by the browser when an HTML document loads inside it now ultimately what we want to do is interact with the HTML document from our JavaScript code to do things like change or add or remove content so once the document the HTML document is loaded in the browser the browser creates an object which models this document and this object is called the document object now it contains many different properties about the HTML document and many different methods that we can use to interact with the HTML document so whatever you want to do something like remove an element from a browser or responsibly user clicking a button or add something to the browser what we do is we do that via the document object now we can see this document object in action if we just open up the console in a browser window so then in a browser if you open up the console we can just come down here and type document and press ENTER and we're going to get this document object remember this document object is created by the browser and it models the HTML page so if we expand this you're not going to see what you probably expect and we're not going to see different methods and properties available to us on this object instead inside the console what we see is a visual representation of the HTML page with all the different elements so we can expand each one of these and look inside them now if we go to elements it looks very much like this thing over here with all the different elements that we can expand so that's what we see if we type the document object out inside the console now we do have access to a load of different properties and methods on this document object and if we just say documents and then dots we can scroll through all of these different things right here and you can see there's absolutely tons of things we can use so for example I could say document dot location and press ENTER and we get this information back about the location which includes an H ref right here and if I say document dot and I'm going to go to URL then we just get back the URL which is up here ok so there's loads of different properties also we can use methods like document dot get element by ID or by class name or by name or tag name etc so there's loads of different methods we can use as well so programmatically the document over here is modeled by this document object created by the browser and inside our JavaScript code over here when we start to code we have access to that document object and we can use it to interact with the HTML pages using those different properties and methods but the Dom also describes how a document locks in a visual way too and having an understanding of that is going to help us a lot when we come to interact with it so the document object model describes our HTML page as a hierarchical tree of notes so if you think about an HTML page it has all these different tags in it and at the top of the page at the root of the page we have this HTML tag and everything else is inside that then inside that we have a head tag and a body tag maybe inside the head we have a title and some other things inside the body we could have an h1 div div inside one of the divs some P tags and so forth the document object model sees our HTML page as this hierarchical tree of nodes and each one of these elements is considered a node in the Dom now this one right here because it's the very top element inside our document it's called the root node now inside the title inside the h1 and the P we might have some text now they are also considered nodes these are text nodes and these are element nodes so the idea is that if we want to interact with a web page we'd use the Dom to reach into this tree of nodes and we get a reference to a particular node for example the h1 right here so say we've got a reference now to the h1 we can use some different methods on that reference to change its content or change its style or remove it or do something else with it so that's the general premise so I'd like you to keep this picture of the Dom in your mind because it will help when we start to talk about the relationship between nodes and traversing from one element to another so now we have a rough idea as to what the dummy's and we know we can use the built in document objects interact with the webpage let's kick on by seeing how we can reach into the DOM and actually select elements and get a reference to them so then when we work with DOM and we're adding removing or changing content on a web page there's a couple of steps involved now the first step is to decide which element on the page we want to either add some content to or remove content from or change in some way and then reach into the Dom and get a reference on that element so that's the first step and this action of reaching in and selecting elements is known as querying the Dom so once we've done that first step then we're in a position to carry out the next step which is the part we actually do something with that element like change its content so for now we're just going to focus on the first step reaching into the Dom and getting a handle or a reference on certain elements and nodes so that we can do something with them later first of all let me take you to the index page and we can see a few different elements on this page so we're gonna try querying the Dom for these different elements so we can see we have three P tags right here one with a class of error now say for example I wanna reach in and grab this P tag right here and get a reference on that element so the first thing we're going to do is store our reference to this element in some kind of variable so I'm gonna create a constant and I'm going to call it para for paragraph and set it equal to something now remember we use the document object whenever we want to do something with the web page so I'm going to say document first of all then I'm going to use a method on that document object called query selector so this in my eyes along with another query selector method I'll show you in a minute is at the best way to actually grab an element from the Dom or query the Dom so all we do is place a CSS selector in here as a string to whatever element we want now if you need a refresher on CSS selectors then check out my youtube series on CSS I'll leave the link attached this lecture but essentially if we want to grab the first P tag right here we can just say we want P and that is going to grab that tag now what this does is it goes into the document and it goes from top to bottom and it grabs the first P tag it comes across and then it ignores the rest of them okay so this is okay if you want to grab the first P tag now what I'm going to do is just log this to the console console dot log para oops para and save it and let's view this so now we can see this P tag so now I have a reference to this paragraph tag inside this constant and then later on we can do things with that paragraph tag like change the style of it or delete it I'll change the content etc okay so imagine now we wanted to get something else imagine we wanted to get this P tag right here how would we do that well we can't use this selector P because that gets the first one it finds but we can use the class selector because this has a class of error so in CSS the way we do that is by seeing dots because this is a class then the class name error so if I save this now it's going to get a reference to that paragraph here in this thing right here and then we'll log in that to the console so save it and check this out in a browser and now we can see we have this thing over here now what if I go to the index page and down here I add another div give this a class of error and then say this is another error now imagine I want to get this thing right here well what can we use we can't use the error class because that will just grab the first error it comes across which is this and ignore the rest we can't use a div because it would come across the first div which is right here so we have to combine these we want a div which is an error and the way we create a CSS selector for that is by saying div dot error this gets us a div with a class of error and that's unique there's only one div on the page with the class of error so if we save this now and come over to the browser we can see now we have this div again if you need a refresher on CSS selectors make sure you check out my CSS playlist on YouTube the link is attached to this lecture but you always have the browser to help you out if you're not sure what selector is you can come to the browser and if you wanted to get a selector for something you could right-click it inspect it and then inside the elements tab highlight the element you want a selector for right click it go to copy and go to copy selector and that gets us a unique CSS selector for that element so if I now go over here and paste that inside here that would get the h1 and you can see we're looking for the body and then the first h1 child so save it and let's go to the console and we can see we get that h1 okay alright so that is the query selector right here now what if we wanted to grab multiple elements we don't just want to go in and grab one particular P tag for example we want to go in and grab all of them and do something with all of them well we can do that using another version of the query selector very similar it's called query selector all so I could say Const Paris plural and set that equal to documents query selector all and then we pass in the CSS selector well we just want the P tax so that is going to go into the document and it's going to get a reference to all of the P tags and it's going to store it as a collection inside the Paris constant so now if I console dot log Paris save this we can see this over here and it's a node list and we can see these three different things in it PP and Peter Arab so these three P tags it's gone in got a reference to all of those and it stored them in a single node list now this node list looks very much like an array but it's not an array we can't use all the array methods on a node list but we can do some things with it like an array we can use square bracket notation to select a single element from that node list so for example I could say console dot log powers 0 to get the very first element save that and we can see the first P if I do two it's going to get the third one remember this is because javascript is zero-based we start at 0 then 1 then 2 and we can see we get the third one right there okay now much like an array we can also use a for each so I could say something like powers dot for each and then we'll take each paragraph that's the singular that's what I'm calling it this is an arrow function with this parameter so it cycles through the node list and for each individual node we get access to that inside the callback function and we can just say console.log the power and let's pass semicolons on save it and down here we can see it's cycles through them and we get each one log to the console the last one is log twice because we also have this down here ok so we can use for each on node lists as well which are basically just a group of elements a group of notes ok so let's do another example I'm going to say Const eros is now equal to documents query selector and we want all and then we want the errors so dots error so anything with a class of error that's this P tag and this div tag so we want both of those in a node list so let me save and save over here and what we're going to do is log out the errors this time save it in preview and now we can see we have a node list with two items Peder error and div dot error as well so now we've got both of those so these two methods query selector to get a single element and query select all to get several elements they in my opinion are the two best methods to select elements from the HTML document but there are other ways to which can be useful at times and we're going to have a look at those in the very next lecture so in the last lecture we saw how to use two different methods query selector and query select all both on the document object to query the Dom and grab elements from it now the query selector that grabbed a single element but the query selector all it grabbed multiple elements based on CSS selector now in this video I'm going to show you some alternative ways to query the Dom to grab elements and I'm going to show you three in total the first way I'm going to show you is to grab an element by its ID so the way we do that is by first of all creating some kind of variable I'm going to call it title and set it equal to documents and the method we're going to use is called get elements by ID now if we look inside our index page we can see we have this h1 right here I've given it an ID of page - title now in an HTML page you shouldn't have more than one ID of the same name so there shouldn't be another ID down here with page title there should only be one ID of that name on the page so inside here all we need to do is place in a string the ID now we don't need the hash symbol which we would do if we were using query selector to select an ID that's already implied in the name we're already selecting an ID we just need to specify the name of the ID and that is page title so this goes out and it gets a reference to this page title ID element which is the h1 so now if I say console dot log and the title we should see that in the console save it and check this out and while we get it right there cool so the next one I want to show you is how to get elements based on their class name so let's come down here I'm going to say Const errors because we're going to go out and grab the errors and that's going to be equal to documents dots get elements by class name and notice the difference here elements is singular so this only ever grabs a single element this here is plural so it will grab multiple elements if there are multiple elements of that class so inside index we can see this has a class of error and this has a class of error I want to grab both of those so I can enter the class name in here again we don't need the dots as we would do in a CSS selector using query selector it's already implied that we're getting a class in the method name so we just pass in the class name without the dot right there now if we log this to the console errors oops we need to do this correctly errors and save this so look what happens okay so we get this thing right here now this is an HTML collection in the last video when we use query selector all we saw that we got a node list now these two things are similar but not identical like a node list we can still use square bracket notation to get a single element from that list or that collection we can say console dot log and then errors and we'll say zero to get the first element for example and it's still going to give us that back but we cannot use the for each method on the HTML collection if I try to do this let me come down here and say errors dot for each and then inside we'll do a callback function with an error parameter this is each individual error this is not going to work console dot log error and save this we can see we get an error we can see errors that for each is not a function so we can't use for each on an HTML collection okay so what I'm going to do is leave a little document attached to this lecture just showing the different things we can do with a node list and an HTML collection so you have those clear in your mind but anyway this is a way to grab elements based on their class name so let me just delete that and I'm going to comment all of this stuff out for now and this stuff up here so it's not putting us off in the console and file it I'm gonna show you how to get elements based on their tag name so I'm gonna try and grab a reference to all the P tags in the document so I'm going to be looking for the tag name P so the way we do this is again by storing it in some kind of variable and setting it equal to document get elements by tag name so they're all self-explanatory they're quite easy to remember and we're just passing the tag name as a string right here so this goes out and it grabs all of the P tags on the page and it's going to store them again in an HTML collection inside this power is constant so if I say console dot log and we're going to log out Paris we should see those over here again HTML collection if I want to grab a single one of those I can use square bracket notation so console dot log Paris and we'll just say we want the index of one from there save and we can see that P tag right here so all of these different methods give us different ways to query the Dom it doesn't much matter which methods you choose but anything you can select with these methods you can also select with the query selector methods I showed you in the last video so I tend to stick with using the query selector or query selector all because it's simple and very flexible and you can query any element you need using them also it's useful to be able to use for each directly on an old list which is returned by the query selector methods tag name and class list both return HTML collections which we can't directly use for each on we'd have to convert these into arrays first of all which is just one extra step we can do without but again you can still use these methods and they're nice to know you can use whichever one you're most comfortable with so then once we've done the first step which is querying the Dom for some kind of element that we want to change the next step is to actually do something with it and in this video I'm going to show you how we can change the text inside elements and also the HTML inside elements so first of all let's have a look look at the index page we can see we still have this content right here and I've also added this deal for the class of content of a hit now the first thing I'd like to do is just use a query selector to get the first paragraph over here and then I'm going to change the text inside this paragraph so first of all we need to say Const and we'll call this poet we're going to store our reference to this paragraph tag inside this constant and we'll set that equal to document query selector and inside here we just want to pass in P that is the CSS selector to get the first paragraph on the page so once we have that how do we actually get the inner text over here inside the P tag well I just said the property directly it's called in a text so if we come underneath here I can say console.log and we want the power dot in a set just like that this is not a method it's a property hence we don't use parenthesis like this we only do that with methods this is a property name and what this does is get us the inner text of that element so if we save it and preview we can see that text right here now what if we want to update that text well all we need to do is grab that text and set it equal to something else so we could say peridots inner text is now equal to ninjas are awesome and then if we save that what it's going to do is grab this paragraph get the inner text property and it's going to set it equal to something else so if we preview over here now we can see it's changed on the page and that is pretty awesome that was very simple to do we just reach and grab a reference to the paragraph then use the inner text property to set it to a new text now notice when we do this it overrides the old text completely now if you just wanted to append to the text you could use plus equals so I'm going to save that and we can come over here we still get hello world but it adds on the extra content as well all right in my case I just want to overwrite it for them so now we've seen how to change the inner text of something what if I want to change the text of several items at once well let me just comment this dude out first of all and I'm going to come underneath this time we're going to grab all of the different P tags so we'll say Const Paris that's plural equals of documents query selector all and we want all of the P tags so we get a reference to all of those as a node list and remember when we have a node list we can use for each on them to cycle through it so we could say Paris dot for each and then we pass through a callback function in here that callback function as a parameter we'll take the individual item as we cycle through the node list we're going to call this power but you can call it what you want and inside this callback function what I'm going to do is for now just console.log power dot inner texts now this is going to cycle through this node list of all these different P tags and for each one it's going to fire this function and take each individual paragraph then we're logging out the inner text of that paragraph each time around so we should see all of these in the console alright so we have these different P tags and we get all of this content inside these P tags now what I'm going to do is update the context of each one of those I'm going to say P dot inner text and set that equal or we'll say plus equal and we'll add on new text so we're taking all of the paragraphs and we're adding this extra text inside then we're not overwriting it completely we're just adding on the extra text at the end of each one so save it and we can see an error and that is because we've called it P and not power okay so let's save that and now we can see new text new text new text and new text awesome so that's how we cycle through several different elements and add text or change the text to each one of those elements using for each okay then so that's how we change the text of something using this property in a text but what if we want to change the HTML of something so for example we have this div at the bottom with a class of content and it has a P tag inside it what if I want to grab this element right here then I want to change the HTML inside it well we can do that just as easily so the first step is to get a reference to this so I'll say Const we're going to call this content and set it equal to documents query select all and inside we're going to use the content class and now we have that content variable we can say console.log and I'm going to say contents dots in a HTML or like so so hTML is all cups so not in a text anymore in a HTML so if we save this now we can see the HTML content inside this content div which is just that paragraph tag so that's how we get it what if we want to update it well let me just comment this out and come underneath I'm gonna say contents inner HTML is now equal to an h2 tag and we'll say this is a new h2 and oops we've done all this in capitals so let's make the h2 down here not capital it doesn't matter that this is capitals that's fine and we're going to save this what it's going to do is take this HTML and replace it with this HTML right here so if we save it we can now see this is a new h2 and we can see that element right there inside the content div so like before when we worked with in a text this completely overwrites the content so if I want to just append the content then I would use plus equals instead so and save that refresh and now we can still see this is the content but now we get an h2 as well and if we open this content div up we can see both of those and now in there so plus equals to append or just equals to overwrite it okay so I'm going to use plus equals in fact I'm gonna just comment this out we don't need that anymore okay so I'm gonna go through one more example now I'm gonna imagine we've got out to a database and got a list or an array of people and what we want to do is output a little HTML template for each of those people in the array so what I'm gonna do is first of all say Const people is equal to an array and inside here we'll just have a few people Muriel first of all then Luigi and then Yoshi all right so we have this array of people just imagine we got this from a database or something now we want to cycle through these people and we want to generate a little HTML template or snippet for each person and output that person in the HTML so the first step is to get the people and say for each and then what we're going to do is take the person and inside a callback function we're create an HTML template now all we're going to do is grab the content which is this thing over here and we're going to append to it each time a little template so we're not overwrite in the content for each person we're just adding an extra little bit of content so this is going to be a template string because I want to embed this variable inside it and what we'll do is create a P tag and inside that will output the person so we need our dollar sign curly braces then the person then we're going to close off the P tag so we're cycling through the people for each person we're firing this callback function and we're taking the content over here which is this div currently has a P tag in it we're taking that content reference and we're appending to the HTML we're not overwriting it we're just adding a little bit extra for each person and that little bit extra is a P tag with the person embedded inside it so if we save this now come over here and go to the console we can see an error we've got an assignment to a constant variable so that's because we're trying to change the content directly we need to say dots in a HTML of course and then we're appending to that save it and now we can see these things right here so if we inspect that inside the content now we can see all of these different P tags so that's a good example of when we might use this kind of thing if we have data we want to spit out into the browser but we want to do it in some kind of template way we can cycle through that data and we can output an HTML template for each bit of data in that array so all of this text and HTML changing is going to be hugely useful later in the course when we come to work on our different projects and we need to update the HTML or the text in the browser so in addition to changing the inner text and the inner HTML of an element we can also get and update attributes of HTML elements so if we take a look in the index dot HTML we can already see I've created this HTML code we have an a tag right here with an href attribute going to google.com and this is the text then we have a PTAC with a class of error and this text so if we take a look at this in the browser it just looks something like this so this is an HTML attribute href and this is an HTML attribute there's a lot of different types of HTML attributes that we can either get in JavaScript or set in JavaScript so let's have a look at how we can do that with these elements first of all we need to get a reference to the element that we want to change so I'm going to say Const link is equal to documents doctor query s son Luke door and we want the anchor tag so that is going to go and grab the first anchor tag we come to which is this and store it in this reference right here so now we can use that and what I'm going to do first of all is use get attribute to get the H ref attribute right here so whatever the value is here and I'm going to log this to the console so we'll say console dot log then we want the link and then we want to use a method called get attribute and this gets us an attribute now we need to pass it as an argument what attribute we want to get as a string and we want the H ref attribute that's what this thing is called so if we save this now and prove your we should see this over here so that is the value of the href attribute and that's how we get an attribute okay then so what if we want to change the attribute or set an attribute well I can take the link then I can use a method called set attribute instead of get attribute and this time it takes two arguments first of all what attribute do I want to change well I want to change the href attribute secondly what do I want to change it to what is the value of this attribute well it's going to be HTTP double forward slash and then www dot the net ninja code at UK so if I save this now and preview if I inspect this element then we're going to see the net ninja code at UK as the value of this attribute now I'm also going to change the inner text so we'll say link top in a texts and set that equal to the net ninja website okay so now we can see the net ninja website and this is where it goes so that's an example of how we can change an attribute to something else and then that's going to automatically update in the browser okay so let's do another example what I'm gonna do is come down here and say Const message is equal to documents query selector again and this time we're going to grab a different element account type at the minute selector and the element we're gonna grab is going to be the P tag down here so let me pass in P right there and what I'm going to do first of all is log out the value of the class attribute because this is still an HTML attribute we're just going to grab that value and log it to the console so console dot log and we want the message and we're going to use the method get' attribute to get an attribute and the attribute we want to get is the class attribute so let's see what happens over here we can see error which is the class of that tag so we can also change this I'm gonna say message dot set attribute oops set attribute and we're going to set the class attribute and we're going to set it to a value of success so instead of error now it should be success if we go to elements we can see now it has a class of success awesome so this would be useful in a case where for example a user fills out some kind of form if there's an error we can change the class of the form to error to maybe make it red or something like that and if it's successful we can change the class of the font of success to make it green around the border or something like that okay so if we want to set an attribute to an HTML element that doesn't already exist we can do that as well so far when we've been setting attributes here we've been setting attributes using attributes which already exists in the HTML now for example I could add on a style attribute from JavaScript to this P tag and I can do that using exactly the same method it's just set attribute and I'm going to set the style attribute and inside here we'll just say the color is green okay so it doesn't matter that this attribute doesn't yet exist on this tag if it doesn't exist javascript is just going to create it so if we save it now and preview we can see the text is now green because we now have this style attribute right here applied to it so any HTML attribute you have in your tags you can either get or set this way and that is going to be very helpful in a lot of cases so in the last lecture I briefly showed you how to change the style of an element by directly setting the style attribute of that element using set attribute but there's one major drawback to that so let me demo this first of all inside index.html we just have an h1 it has a style attribute and that style is just color is orange so looks something like this in the browser now imagine we want to add a new style to this style attribute well if we come down here we've got a title reference already we've stored that in here that is query selector and we're getting the h1 which is that so we can just say title and then you set attributes we're going to set the style attribute and what we want to do is add a margin so I'm just gonna say margin is going to be 50 pixels so what's gonna happen when I do this well if I save it and come over here we can see we get that margin but it's totally overwritten the orange thing right here because we call it orange in the HTML so when we use this method set attribute especially when we come to styles and we want to add additional styles it's just going to completely overwrite what's currently there so I don't want this behavior I want to be able to add extra Styles instead of just complete the overwrite in them so how can I do this well we can do that in JavaScript using the stale property so first of all I'm going to log this to the console so we can take a look at it I'm gonna say console dot log and then we want the title which is this thing up here then we say dot style this is a property of this element so that if I save this now and preview over here in the console we can see this big object and it has all of these different properties these are all CSS properties and we can see most of them are empty but if we scroll down to color we can see the color is orange because that's what we set it to be in the HTML so we can use this style property to add styles on the fly or remove them as well so imagine I want to get the color style property and I just want to see that I could say console.log we want the title dot style and then in the style object over here when we logged it to the console we just grabbed whatever the property name is that's the CSS property name right color so we can say dot color and that should give us orange so we see that right there awesome now what if I want to add Styles then well I can come down here and say title dot Styles or style rather then the property names that I want to add a value to now it can be any one of these different properties listed right here this is every single CSS style or CSS property name so I can say something like margin and I can set that equal to something it's in a string 50 pixels now if I save that and refresh we see we get the margin if I inspect we can see this now has a margin but it also still has the color we've not overwritten that we've just added a new property so for that reason this way is better than this way okay so let's do another example let's say I want to change the color style so we already have orange right here if I want to change that I can say title style is equal to crimson save that and let's view this in a browser and we can see that updates the color now and we can see over here the color is crimson and it still has the margin so again it's not overwritten anything well it has it's over it in the original color but not the margin all right so what if I want to do something like the font size well in CSS the property is fonts - size and then we give it something but we can't do that in JavaScript because it looks at this and says okay well you're taking the fonts and you're trying to subtract this thing right here the size so in JavaScript when we have a double barrel property named like this we take away that and we use camel case like so so what we can say is title dot style dot font size and set that equal to something I'm just gonna set it equal to sixty pixels save it and check it out in a browser and now we can see it has a font size of sixty pixels as well now if you're unsure of what the name will be remember always refer back to the style property and just look inside that so if we open this up we can see all of the different names right here okay so for example border left color you can see it's camel case okay so if we want to delete a style we can just grab it by saying title style then the property name for example margin then I'm going to set that equal to an empty string so it was 50 pixels before when we set it here now I'm setting it to an empty string so it basically removes that property so if I check this out we can see the margin has now gone and inside the style attribute we no longer see margin so most of the time that we're adding or removing just a single style I'll use this way of doing it rather than the set attribute method but a lot of the time instead of just adding inline Styles this way it can be easier to predefined all of your CSS classes in a style sheet somewhere and then use JavaScript to add remove or change classes on your HTML elements and we'll see how to do that in the very next lecture okay then so in this video I want to show you how we can easily add and remove classes from elements so first of all you can see I've got this dummy content right here we have a P with a class of error and this stuff inside now I've also linked up a style store CSS stylesheet in the head and that's over here just to very simple Styles one for a class of error padding 10 pixels color crimson and a border of crimson as well and one for a class of success padding 10 color lime-green and a border of lime-green as well now currently this has a class of error so if we view this in a browser we can see something like this it's red text with a board of green if we change this to success then we see the green text and the green border okay so what I'm going to do is show you how to change classes from the JavaScript so let's get rid of all of lust lessons code and instead what I want to do now is grab first of all the PTAC so this thing right here so I'm going to use the query selector to do that and store it in a constant called content and that's equal to documents dots query selector and then the P tag okay so now we have a reference to that what I'm going to do is log out a whole list of this element classes so I can do that by saying console dot log then the content dot class list so this is a property and it gets us a list of all the different classes this element has so in the console we can see we get a Dhamma token list we can see just one thing in here error so that's this class right here now if I give this another class I'm just going to call it another and also test I'm going to save it and we can see now we have all of these different classes inside this token list so that's a way to get classes that an element has now what if we want to add or remove classes well let's try first of all adding one so I'm going to say content dot class list to get that Plus list then we can use a method on this class list called add and that's how we add a class now inside here we pass a string off the class that we want to add so say I want to add a class of error and what I'm going to do is to begin with I'm going to get rid of this so it doesn't have that class save it and over here I'm now taking this content this P tag and I'm adding a class of error to it so if I save it now even though I removed it from the HTML when we first get that class list at the top of the JavaScript file it doesn't have a class yet but then we add the class and now we can see it right here so then how do we remove a class well I'm going to just duplicate this and change this to remove and then that is going to remove the error class so if I save it then we're not going to see a class anymore ok so then that's how we add and remove classes now I'm going to add the success class so I'll say content dot class list dot add and success and we should see that this is now green because we have the success class awesome ok so that's a simple way to add and remove classes from tags in the HTML page so let's just comment all of this out and I've actually got a little challenge for you to do so I'm just going to copy a bit of HTML from my github repository right here and I'm gonna paste it inside over here so let me get rid of that and then paste in this content and it's just a series of P tags now some of these P tags has the word error inside and some has success success and some have none okay so they don't have error or success now the challenge is I want you to query all of these elements and then I want you to cycle through them and I want you to give any tag a class of error where error is inside the text and I want you to give any tag a class of success where success is inside the text ok so if you want to pause that here and then try it yourself then unpause it and see how I do it ok then so this is how I'm going to do it so if we go back over here first of all I want to get a reference to all of those different ptex now to do that I'm gonna say Const call this Paris and say that's equal to documents dot query selector all and we want all the Pete acts so that's all the P tags first of all remember this returns an old list and we can use for each on an old list to cycle through them so I'm going to say Paris dot for each and for each paragraph I'm going to pass that into the callback function I'm just going to call it P you can call it whatever you want then I want to check if the text inside each paragraph as we cycle through them has either error or success in it now that in previous lessons when I showed you how to get the text content of something I've used in a text so we could say console dot log for example P dots in a text like that okay and if we do this then we should see all of that in the console now that is a fine way of doing it but another way of doing it is by using the text content property and that's going to get us exactly the same so what's the difference then well the difference is if we use in a text then it will get us all the text that's visible so say for example I have something here like a span tag surrounding this error and let me just put the closing tag there and I give this a style equal to display:none right well what that is going to do is hide this error from the page now if I look in the first paragraph we don't see error so if I use now over here in a text what that does is get us all of the visible text inside that element now error is no longer visible so we don't get that now if I use text content let me show you this text content what that does is get all of the text inside the tag regardless of whether it's hidden or not so if I save this javascript file and come over here now we can see we get all of that we get the error text as well even though it's hidden so what I'm going to do in this example even though you could use in a text I just wanted to show you the difference I'm going use test content so I'm gonna say right here that we want to check if the text content of any of these pee tanks as we cycle through them has either error in it or success in it so let's check for the error first of all so let's do a little if statement will say if and then we want the pee the paragraph that we're currently iterating through dot text content dots includes remember we can use this method to see if a string and that's all this is at the end of the day it's a string of text we can use this to see if it includes a certain word or phrase so I'm gonna see if it includes the word error so this returns a boolean if it does include that then it's going to return true and we're going to find this code if it doesn't it returns false so if it returns true it means that that paragraph that we're currently iterating has error inside the text and if that's the case what we want to do is give that a class of errors so we'll take the paragraph we'll say dot class list and then we'll say dot add and we want to add the error class simple so if we save this now and preview it in a browser we can see anything with error inside it is given this error class and we can inspect to make sure that we have that error class on those awesome now we need to do the same thing with anything that has success in it so we're going to do another Eve check to say if P text content and again if you wanted to here you could use inner text I'll do that here just to show you dots includes and we're going to see if it includes now success if it does then this returns true and we'll fire this code block and inside we want to take that paragraph tag and give it a class so we'll say class list dot @ and we want to add a class of success like so so save it and let's have a look over here and we can see now anything we success in the text has this class of success ok so that's how we add and remove classes now there's one more thing I'd like to show you and that is how to toggle classes so we've seen add and we've seen remove up to either add or remove classes but what if we want to toggle a class so if an element has a class we want to take it off if an element doesn't have the class we want to apply it well we could use the toggle method so what I'm gonna do is first of all come over here and I'm just gonna give this h1 a class equal to title now I'm going to grab that over here by saying Const title is equal to document dot query selector and I'm going to grab the title class so we have that now now what I want to do is just say title dot class list and I'm gonna toggle a class and that class is going to be test so currently it doesn't have a class of tests but if I use the toggle it means that it will give it that class of text so if we take a look at the h1 we can see it has a class of test now now if it has a class of test and we use toggle again then it's going to remove that class so if we save that and now preview it we can see it gives it to begin with then because it has it and we run it again it removes it so now we no longer have it so there we go add remove and toggle three methods that we can use on this class list property of elements to add remove or toggle classes okay they're my friends so that is the end of this free series here on YouTube but if you do want to take your JavaScript skills to the next level and learn more advanced concepts like interacting more with the browser events Ajax databases and object-oriented programming as well as put what you learn to good use by making five different JavaScript applications from scratch then make sure you check out the rest of this course on udemy there's another 13 hours worth of content on there which covers a load more stuff it really will black belt your Java Script skills and put you in a great position to be able to make your own JavaScript driven applications so the link to that course is down below and I've applied a discount to it so that you get it for nine 99 instead of the full price it's normally up so I really hope you've enjoyed this so far and hopefully my friends I'll see you over at the rest of the course on udemy soon
Info
Channel: The Net Ninja
Views: 143,942
Rating: 4.9711342 out of 5
Keywords: javascript, javascript tutorial, tutorial, modern javascript, modern javascript tutorial, es6, es7, es8, javascript for beginners, js, js tutorial, modern js, js tutorial for beginners, javascript tutorials, tutorials, dom, document object model, javascript do, javascript document object model, document, document object, dom tutorial, document object tutorial, document object model tutorial, query selector, querySelector
Id: wKBu_dEaF9E
Channel Id: undefined
Length: 53min 38sec (3218 seconds)
Published: Thu Apr 18 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.