DOM Manipulation -- The Modern JavaScript Bootcamp

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey welcome everyone we've made it to my very favorite topic in the course and honestly my favorite topic in all of teaching web development the dom so this is very exciting stuff in my opinion i look forward to it every time i teach and when i teach boot camps in person it's my favorite week favorite two weeks it's really fun stuff because we start to connect javascript with html and css this is where i think javascript starts to become a lot more exciting um and certainly more visual you can start to make things with interfaces things that you can see enough of the console.logging so i always look forward to it hopefully you're excited about it especially if you've never worked with the dom you don't know what it is there's a lot to cover here it won't fit into one section we have multiple sections i have a couple of examples i'd like to show of things that we could build after you learn how to manipulate and work with the dom so there's some simple ones like here's a form where as i start typing notice the placeholder text here that says last name if i put something in here like chaplin notice how the text went down below as a label and then if i delete it it goes back up very simple little tiny touch but that's done with javascript so we have the form that is just html and css we don't need javascript to make that work if i comment the javascript out well i just deleted it let's comment it out we still have the form here but now we're not getting that interactive element it still looks the same but we don't get that behavior here's another example this is a fun well fun is relative it's a game that is a memory game where you have to match different cards and flip them over i'm terrible at it but i really like the interface at the beginning when you start you get this nice little flip of the card when you click instructions and then you can click here to actually begin the game and select a level so the content itself is html and css if i comment all of that out select it comment it out we still have the exact same interface it just doesn't do anything i'm clicking maybe you can hear that through the mic but we don't get any behavior we're just seeing that content it's basically static little blocks of color with some letters but we add javascript in and now they do something when i click and i can play the game go to casual like i said i'm horrible at this game but the just very act of clicking on something and having it change in any way changing the color having it flip revealing the symbol that is all javascript the cards themselves are html and css it's very hard for me to even attempt to play this while talking so uh i'm already terrible to begin with but as you can see we've also got this timer going across the top highly stressful i'm just clicking randomly at this point and one more match before the end all right so again this is all javascript functionality this is javascript that is making the game logic that is checking if we get a match it's checking oh jeez it's checking to see if a card has already been clicked on or if the timer has finished if you still can play or if it's game over here's another example this is another nice form where we have different steps of the form little animations that are triggered so we go from step one to step three each time i click i'm just seeing html and css if i remove all javascript one more time we still have the exact same content it just doesn't do anything i can't go from one step to the next we add javascript in and it's now an interactive almost like a different set being shown on a stage when you go see a musical or a performance a new set being swapped in and the colors are changing up here to tell you which step you're on so nothing crazy but this is all done with javascript all the interactivity and then now for something a little crazier much more complex this is on youtube this is a a recorded live stream of a really cool musician very funny guy mark reby yeah it doesn't matter who it is anyway over here we've got comments hopefully nothing super inappropriate and as i play the the video you can see these comments start to come in and they're synced to when they were actually submitted back when this was live i can click to hide i can show it again this is all happening through javascript these elements are being added to the page in conjunction or in time in sync with this video they're being added here so even something just like hiding and showing is done with javascript being able to pause video and have this stop we don't get those new comments now that's done with javascript if i fast forward i get new comments that's done with javascript so javascript the dom very exciting stuff this is where we start to take html and css and control it update it or even just read it and understand it using javascript so something like this is made by a team obviously a huge team at youtube but things like a form or a memory game the code is really not that bad but the thing about the dom that i'll tell you right now is that you have to use tons and tons of methods and properties that we haven't seen before so remember when we saw arrays or we saw strings and i talked about here's you know 20 methods that arrays have when we work with the dom we have at least 20 maybe 50 different methods 50 different properties and it takes time to get to know the ones you'll use the most and it's also imperative that you don't try and understand and learn every single property that's something i'll bring up as we make some more progress the dom is just a huge thing there's so much to that you could stress about trying to learn and memorize don't approach it that way we're going to go step by step and in the next video we'll take our first step into this beautiful promised land of the dom before we move on there are some prerequisites some things that you need to be comfortable with before you can really master the dom before this content will make sense to you those topics are basic html and css the good news is that html and css are really pretty easy to learn the basics of at least we're not talking about making beautiful websites we're not talking about crazy complex layouts that are responsive you just need to understand how to create simple elements on a page how to nest things together how to work with ids and classes how to write simple css selectors to select based off of elements and classes and ids maybe attributes you need to understand how to change colors with css and fonts and how to resize something the basic properties so if you don't have that understanding right now i recommend you take an hour or two to go follow a tutorial online you can check out my youtube channel i have a basic html and css intro but there are also tons of great courses paid and free and books and free blog posts you don't need to go you know buy an expensive course or even buy anything just take some time and set it aside so that this section in the next few sections actually makes sense to you because this stuff is really exciting it's fun but if you don't have that understanding of html and css it's just going to be intimidating and make it a lot more challenging than it needs to be because this dom stuff is actually not hard where it gets tricky is when people try and learn it before they understand html and css so i'm going to do a little demo slash assessment that you can self-assess based off of i'm going to write some simple html and css to show you the level of understanding i'm looking for so i have an html file already created i'm going to add some simple elements in here we'll add an h1 and this will say my webpage i'm going to add a simple ul an unordered list with a couple of lis first thing second thing and third thing so i have an li here or three allies in an unordered list i'm gonna add an image i'll set the source to be this nice grizzly bear image from unsplash.com nice images that we can use for free and i will also go ahead and add in maybe a paragraph tag or two paragraphs just uh let's do some alarm ipsum so i can just type lorem nvs code and then i'll add another one of those lorem just random text i'll add an id to my image and i'll call this image we'll just call it bear photo so if you're still with me if this is all making sense and feels like very basic stuff that's good news if any of this is confusing you're not sure what these elements are you you don't know what an idea is or a source take some time go learn that stuff because you'll need it you absolutely need it for the next couple sections i don't want you to feel bad or get lost all right so we have our h1 i'll also add a class to my allies two of them at least this class will be called um special okay so i have two paragraphs i have my h1 i have lis that have a class of special i have an li that doesn't and i have an id for my image of bear photo now i'm going to make a style sheet so i'll just make my file here i'll call it app.css and i'm going to start by styling my h1 just something simple color purple font size 20 oh no that's going to be very small how about 60 pixels so i haven't connected my style sheet but let's just make sure my content is showing up all right now i'll connect my style sheet using a link tag and the href is app.css and my h1 should change it's purple now and larger so if this syntax is new to you you haven't seen it you don't know what font size does or color i guess that's pretty self-explanatory but if you're not sure about this syntax here then take some time and review that let's also go and select the bear image so here's the first little part of the assessment how would we style this bare image to give it a width of 250 pixels using the id all right so i'm going to come in here and select it with bear dash image and i need to make sure i add in or bear photo oh jeez horrible name can't even remember it i need to make sure i add in my hash symbol there to make it clear it's an id and i'll give it a width of 250 pixels refresh my page much more manageable the next part of the assessment i'd like for you to make the class of special these two allies i'd like them to be teal and 30 pixels font size and give them a one pixel border also teal so we'll select the class which was called special i need to use the dot because it's a class and i'm going to start with color what did i say teal and then font size i think i said 30 pixels and border was one pixel teal let's see what we get all right so there is my special class so i've styled the h1 the image with the id of bare photo and the two items the two allies that have a class of special it looks horrendous it's very gross but this stuff is very important don't worry about the styles but if you feel like any of this was new or confusing you need some clarity on it go look online and get some practice now here's one more thing that you could use as a little assessment let's add in a form all right so i'll add a form element right here and in this form i'm going to add an input type equals text i'd like to give it a placeholder of um what should we do bear name and then another input below that and instead of type equals text what are our options here we'll do type equals how about password and then give it a placeholder of password and then one more input we'll do type equals submit we'll refresh and we have our form here what i'd like you to do is select only the input that has type of password and give it a different width you can change it to smaller larger just give it a different width and a height so you'll have to select based off of the type not off of input don't add an id don't add a class select it as is so i'm going to do that over here if i just did input like i did for h1 that will target all three and if i do height let's do 50 pixels with 100 pixels that does work but i only want to target this one right here so i can add in an attribute selector type equals password and now only this one is affected the other inputs are unchanged so that's it for the stuff i mean that's not everything you need to know but that's a general sampling of the the kind of html and css experience you need you need to be able to do basic styles understand css syntax key value pairs semicolons selecting based off of classes ids elements attributes there's a bunch of other selectors and we may come across some of them in the course but this is most of what we'll be selecting based off of in our javascript and then as far as elements things like inputs definitely paragraph tags h1s all the headings buttons list items all the different text elements paragraphs semantic elements like block quotes sections articles you don't have to be an expert in everything just i want you to be comfortable enough where you're not focused on the html and css so much and trying to understand it that you're missing out on the dom stuff which is fun all right so now we're going to move on to the dom again please take this seriously i mean you're obviously able to make your own decision and do what you think is best and if you want to just plow ahead without html and css experience it's definitely possible you'll pick it all up at once but for the best experience i recommend that you you get some practice first take some time away for just a bit you're not going to miss out too much the course will still be here for you get better with html css and then come back all right so let's get going all right now that we have all that housekeeping out of the way all the html and css prerequisites we can now dive into the dom very fun stuff we're going to start in this video with kind of a taste of the dom i'm going to show you some code different snippets we'll play around and tweak a web page and the the goal is not for you to understand every line or remember it because i'm showing you code that we'll see in this section later on or two sections from now we're kind of looking ahead so it's it's more of a sneak peek okay so the document object model or the dom is our window into html and css and the web page in general through javascript it is our portal into the world of a web page so we can write javascript that can figure out how many h1s are on a page or how many inputs are in a form or we can get the value from a form if a user is typing into the form we can change the value of a form we could change images make them bigger we can change styles of anything we could add animations we can listen for clicks or drags or hovers or any sort of event that a user could trigger and then have some behavior that happens in response a user clicks on a game piece and it will change color or if a user clicks and drags a chess piece when they drop that chess piece you should check we should write code that checks is it a valid move if it is then move that chess piece to the square if there's a piece there already then replace that piece and remove the captured piece from the board we add logic in with javascript that controls that interacts with that reads and understands the contents of a page and the key thing to understand about all of this is the object part document object model when your web page loads up whatever the web page is this simple one that we were doing here in the last video when it loads up the browser is going to turn it into a bunch of objects just javascript objects and these objects are all constructed and put together to form the dom it is a virtual representation or a javascript representation of the content on a page and it consists of a bunch of javascript objects so i probably spent way too long making this image but we have html and css and some other stuff that goes in and the browser interprets it it reads it and it creates the dom for you it spits out javascript objects representing the html and representing the css so here's a simple example of what i'm talking about if this was our html a very simple web page we have an h1 we have a ul we have two lis the browser will read this in which on its own doesn't mean anything it's just text it's text content the whole job of the browser is to display it in a way that makes sense to humans to make this larger to make this a bullet point if it's inside of a ul so the browser reads it it does all of that and at the same time it creates a virtual representation a javascript object of the h1 there's another object for the ul another object for the li and another for the li so that's what this is representing over here each one of these little circles or nodes is an object they're telling you that i'm an object me too in case you had any doubts so they're objects and those objects have a bunch of different properties the simplest one that we could see from here would be what their content is what text is inside the object what are plants okay so we have one that has a property called text or something like that it's actually called inner text set to water plants we also have tons of other properties for different attributes uh css styles we have methods that we can use so that i could delete one of these with javascript and it would be deleted from my web page i could update one of them and change the text i could even change the type of element i could instead of having an h1 i could replace it with an h2 all of that is done through javascript where we interact with these objects all right so now for the part that is the taste of the dom a little preview of where we're going so i'm on google.com just a regular home page i'm going to just type some code in the console the first thing we'll see is proof that we get a bunch of objects the dom just consists of objects so why don't we pick something maybe this button right here it is an input does it have an id it doesn't have an id okay this one has an id is this the i'm feeling lucky button i'm going to copy this id and use that to select that element so this is new you haven't seen it before or at least not in this course don't worry about it i hate saying that but don't don't stress about what it is okay so if i save this to a variable const button object if i look at that button object i've selected based off of some id and i have a representation of it unfortunately in the console it looks like it's not an object it looks like it's just html but if i do console.dir which we've seen a couple times button object and open this up you can see it's just a regular javascript object it's massive it has tons of properties tons and tons of methods and properties here and they all relate to this one button let's take a look at one of them how about the value of the button if i scroll down go down to value it's set to i'm feeling lucky we also have things like classes and ids if i go up to i where are you h i j k there we go here's the id we have attributes like hidden so this is not a hidden element so it's set to false we have tons of other things that we're not going to get into right now but you can see that it's an object and everything we see on this page is represented with its own javascript object but let's start with this one so we have our button obj and i can read the value of that button which is i'm feeling lucky i could also change it i could set it to something else i am not lucky does anybody use the i'm feeling lucky i haven't not on purpose at least and we can see we just changed it it now says i am not lucky so that's our first interaction with the dom the page loaded all this html was turned into stuff we see visually and at the same time it was turned into javascript objects we can select and interact with those objects we can change them in javascript it's just like if i had an object here where i had a value set to 4 just call this o and then i said o dot value is now equal to 56. the main difference of course is that when i change o dot value nothing happens o is different but there's no side effect the browser doesn't care it's not changed but when i change one of these objects from the dom there is an impact it's reflected in what we see so changing this javascript object is linked to seeing that change in the page so when we change a style when we change the text when we add new elements we do it through javascript objects and then the browser knows about it the browser knows hey this thing just changed i better update it for the user or in the browser so that we can see that changing and we'll try one more fun mildly fun thing not not exceedingly fun we're going to add an event so when i hover over this button i want to console.log something or change the text although it's already being changed here we get this nice animation that's from google we're not going to deal with that so why don't we just start by alerting something so we have our button object btn obj and again this is something we haven't seen before but we will see it so we're not going to go into detail here but this says add an event listener whoops add event listener to the button the event we're listening for is a mouse over and then here's the function i want to run when i do mouse over and i'll just do an alert hi okay let's see what happens there we go i get high every time i hover over that button anywhere else it doesn't change nothing happens but i go over that button we get a nice alert so we could replace that code with anything else usually we don't alert we might change the the content of the button we might instead we could i mean we could do anything we could change the color we could add new elements to the page we could delete every single thing from the page we could animate things we could send a request to get information from an api it doesn't matter what we do but the point here is that we can do it we can run code when an event happens or when it occurs based off of a particular element in this case that button so we will get to events in due time first we've got to start with the basics of the dom and in the next video i'm actually going to do one more kind of fun demo where we're really going to just wreck this home page for google we're going to animate everything so that it just randomly bounces around and rotates it's going to be kind of fun maybe but if you don't feel like watching that you just want to get to code and you want to start from the beginning that will be two videos from now the next video is just another taste of the dom part two all right so to summarize everything we saw here the dom document object model is just a bunch of objects plain old javascript objects we've worked with them before but not ones this large not ones that have so many methods and properties these are made by the browser based off of the incoming content the html and css other information about a web page it's all turned into a javascript representation of objects that we can use we can interact with and we can change all right welcome back this is part two of our taste of the dom little demonstration so i'm going to go ahead and play around with google the homepage of google again but i'm going to do something a little bit more visual more intense i'm going to take every element that you see on the screen and animate it around randomly so it will just end up being a huge mess to try and use and uh yeah just to show you that we can do things like change styles and move things around and animate them so i'm going to open up my console oh almost there command option j there we go and the way i'm going to write my code instead of just typing it in the console because i'm going to have probably 10 or 20 lines i'm going to make a snippet and in chrome to make a snippet we go to sources and then there's a tab called snippets if it doesn't show up for you you can click the arrow and go to snippets this allows me to write some code so i'm going to click new snippet i can write code and then run it at any point in the browser without having to make a separate file and it will be evaluated and i can do things with the current web page so i'm just going to try something like console.log two plus two i'm going to save it and then i can run it either by hitting uh where's that button right here clicking this or using the shortcut which is what i use command enter on a mac if you're on a pc it will tell you what to use right there so i just ran it and if i look at my console you can see 4 was printed out so we're not going to be using console.logs or anything right now i'm instead going to interact with the elements over here on the dom get rid of that triangle some fun uh top google searches how to make french toast jobs hiring and funny cat videos can argue with that all right so the first thing i'll show you is that we can create new elements super easy well it's relatively easy don't worry about any of the syntax we'll go into the details about how all of this works but i'm going to make a new image i'm going to give it a name my image i'm going to give it a source my image.source equals and i have a url i've copied from unsplash a free image we can use and then i'm going to add this image to the dom i'm going to insert it so i'll do document.body dot append my image and if i run this code i'll hit command enter oh there's my image very large image but it's showing up if i want to amend it to be smaller my image.style.with equals let's do 200 pixels run this code again i'll have to refresh my page and run it now we have this image of a dog wearing goggles okay so that's first bit now if i want to move it around there's a lot of different ways of doing this the best way would be to do it mostly via css but what i'm going to do is in javascript i'm going to generate some random numbers an x and a y coordinate or a position and use that to move the image to that location using a css transform so if you haven't seen transforms in css this is going to be new but it's really just a demo of like cool stuff we can do so don't worry about it what i'll do is get my image my image dot style dot transform and before i animate anything i'll just assign a transform like how about translate and then i give it a number like 300 comma 200 let's see how that looks if i run it oh i think i forgot the pixels that i need to add 300 and 200 pixels let's try that again okay so now i transformed the image i moved it over here i translated it so that's how we can do it just once now if i wanted to do this randomly and i want to repeat it i could do it using a set interval so set interval i pass in my function i'll use an arrow function just for some diversity here and we also need the duration or how long that interval should be so every two seconds we'll run this code and we will transform that image but let's generate two random pixel values and i'm going to use the dimensions of the screen which i can access using document dot body dot client with and client height height so that's something we will see and talk about in greater detail document dot body dot client with times math.random make sure i add my parens and then i'll floor that whole thing as we've seen before to get a whole number so this will give me a random number between 0 and whatever the width of the window is which changes depending on the actual width so here we get a different width versus here we would be getting 400 pixels all right so math.floor i'm going to save that to a variable called x and then duplicate this and do the same thing for a variable called y i'm just getting two random numbers math.for document.body i'm going to do client height here and then i'm going to plug those numbers in right here so this does need to be a template literal not single quotes so i'll put that around my string and then interpolate x pixels and then y pixels and the moment of truth let's see what happens okay we're getting something it's not pretty it's very jerky but every two seconds it is moving around and if i wanted to make it smoother in my css i would add in a transition property although right now i don't have a css style sheet this is google's website so i'll just show you that you can do it through javascript my image dot style dot transition equals and then i'll say one uh what is it all one second let's do two seconds if this interval is two seconds i'll have it take two seconds to translate and does it work oh look at that it's moving all over the place okay so kind of fun we're picking a random x and y on the screen and moving the image that image for the record was not there when the page loaded we're adding it in so we're seeing a whole bunch of different features already we created a new element we updated its source attribute we added it to the page then we added some css to it we changed the width to make it smaller we changed the transition property to make it smoother when it moves and then in a interval we're picking random numbers and using that to generate a translation a transform across the screen every two seconds now for the extra fun part let's do it to every single thing on the page so this same logic but i want it to happen for every element and there's a lot of ways of doing this what i'm going to do is select all the elements using this dot document.body.children again this is getting to stuff we have not seen we haven't seen any of this so please don't worry about it we will get to every every single line of code we're writing here we'll have at least a video addressing it and how it works so document.body.children will give me all the elements that we're seeing on the page i don't want to select every element in the dom because there are elements like script tags and link tags and the title tag we don't want those we want just the stuff showing up so document.body.children i'll just call this all else all elements and then i'm going to loop over all elements inside of my interval so for let l of all else i'm going to pick an x and a y i'm going to use that x and a y to update the transition excuse me the transform of that element so let me make this easier to see instead of my image.style i'm going to do l so i select everything on the page and then for each one i'm going to give it a new transform with a new random x and y and we'll do it every two thousand seconds or two thousand milliseconds we'd be here quite a long time if i did it to everyone whoops all right let's go back try it again run my code fingers crossed all right so we only have the dog image that is transitioning smoothly everything else is just jerking around let's also rotate everything so we could pick a random rotation here we'll call this rotation which needs to be a number between 0 and 360. so we'll do math.random times 360. that should give us a random rotation and then the way that transform works in css is that it wants us to pass in a number of degrees so we'll do it just like this dollar sign uh rotation and then afterwards we need to write d e g for degrees like we had to do for pixels and this should be rotate not rotation let's try it out and there we go things are rotating they're just not animated except for our one image so the last thing we'll do is apply a style to everything in the body we'll add a new part to the style sheet and i'll just paste the code in for that here what i'm saying is make a new css style sheet basically that's what i'm saying and then add in a new selector select everything via css give it transition of two seconds and then i'll add that style sheet in again don't worry about any of this code whatsoever but let's just see if it works i'm gonna run it fingers crossed hey look at that everything's all rotating and going crazy moving across the page it is kind of annoying that this whole thing is treated as one element this i think it's called viewport is the element so we might be able to break that up a bit but you can see what i'm trying to show you is that we can select things we can screw with them in maybe not so nice ways like animating them but these principles apply for everything we would do we can interact with the form get the value out or change an image source to make a slideshow widget we can add events like we saw in the last video we can pick random things and mess with them with random numbers and transformations maybe not all that often but you can do that we can add new styles to a style sheet we can make things have a transition we can create an image out of nowhere and add it to the page okay so i tweaked it ever so slightly before what was happening as i was getting every element in the body which is really just this one div and it contains everything and i was animating this one div so this whole piece of content was animating together but now what i've done is updated it so that i'm animating these elements inside that div instead which you can see here this is what i this line does if i run it now we end up with some independent rotation and moving around anyways the whole thing is useless and silly but it illustrates this idea of changing objects and seeing those changes reflected in the actual browser so everything we've done has been manipulating javascript objects hence the object model part of the dom so really really important idea behind all of this the page loads and all of that juicy content is run through the dom machine the dom maker 3000 obviously not what it's called but it takes that content it understands it it digests it and it spits out a bunch of javascript objects some of which we interacted with in order to make this happen and some of which we created from scratch and then told the dom or told javascript to insert them with the rest of the content okay so now that we've had a somewhat overwhelming taste of the dom now we're going to go into the basics and start from the beginning how do we do some of the stuff we just did we'll go into detail around selecting and changing styles and different attributes and events there's a lot to talk about alright so it's time for our first official video in the the real learning part of this dom stuff we saw some demos we got a little taste of the dom we talked about html and css and what you need to know this is really video one of learning the dom so we're going to start with the most important part of the dom the document remember dom stands for document object model and the dom is just a representation of an actual document made with a bunch of objects and they're assembled into a tree this shape that we see over here there's a hierarchy they're not just sitting out there in some random order they're not in an array for example i mean they could be but then how would we know the relationships between parents and children and the structure so they are put in a tree-like structure here with branches and in every tree there is a top-most piece what we call the root of the tree which is kind of the opposite of a regular tree i guess the roots down at the bottom but anyway we've got the root of the tree which when we work with the dom is an object called document so document is an object you have in every single browser window that you ever open you can type document every web page here's one of mine this one the simple html and css demo if i type document right here i get a annoying printout this is not what it actually is this is the dev tools just showing me the html in the document but if i do console.dir document we can see the actual underlying object now this object represents the entire page this entire document if i go to the mdn page this is actually the docs for the document if i look at document and do the same thing console.dir instead we have another object and they follow the same pattern they have a url right there's a url right there my url is different over here i'm on a file protocol i'm just viewing my html file versus here i'm looking at developer.mozilla.org and the document contains tons of properties tons of methods this is really where we start with everything so all of the other objects all of the other pieces of the dom are located within the document somewhere it's all nested into a kind of large confusing structure if you are trying to navigate it yourself and if you recall from the last couple videos everything that i was doing i was typing document.something document.getelementbyid document.body.children document dot get elements by tag name there's all of these different methods and properties and they're all contained within the document object so the document is the entry point that we use to access the dom to manipulate things to just view the content in the dom but also to add events and add functionality it's all located inside of this one object the document and everything else stems from there so it's created for us automatically we don't just like we don't create the dom ourselves the browser does it when it loads a page same idea the document will be there for you when a page is opened in the browser or when you view a web page if we take a look at my webpage again here's the document that i printed out as an object we'll see a couple other things that might make sense right now how about images this is a collection of images on the page there's one image right now if i go to the mdn version and i look at document dot images we have what 12 images on this page if we go back to my version and we instead look at something like how about document.all right here this is a property that contains every single element on the page things we see and don't see so the title meta tags the head script tags if we have any they're all included here every single one is turned into a javascript object and itself has tons and tons of properties and as you can see here if you were trying to navigate this manually and trying to understand it all this is just completely overwhelming but fortunately we really don't need to know most of it so the main takeaway here is that we get all these objects for free we load up the a web page in the browser whether it's a file or we're going to some website and the dom is created all of it is stored inside of one object called the document but the document has references to all those other objects as you can see here if i go to document.all this is just one way of looking at other elements i've got 12 no what 21 different elements if i do it on mdn that document object dot all has holy cow 18 940 elements and each one is going to be a big massive crazy object that has tons of stuff inside of it so that's it for now the document is our entry point and that's why all of these methods we run all of these properties we'll look at or at least the majority of them start with document.something document.do something so we'll see our first batch of methods in the very next video very exciting i think maybe okay bye alright so now that we've seen the document and all of its craziness all the methods and properties that it holds inside obviously we didn't see them all or talk about them all but you saw how many there are we're going to start by taking a look at the first batch of methods that you should know the most important methods that have to do with selecting so selecting is a really important part of the dom manipulation process typically we select an element or multiple elements and then do something with them so here's a simple example with paint cards or paint chips we select one and then give it a new color or do something with it we could animate it we could uh move it around we could delete it we could select something and then add a new child within it a new element we could select a form and add two new buttons to it we can also do things like add events so we select an element a button we did this early on actually two videos three videos ago we selected a button on google and then when you hover over it we alerted some text so when we want to add some events and interactivity we still start by selecting and there's a bunch of different ways to select using the document i'm going to show you a couple the first one we'll tackle is called getelementbyid this is a method on the document so we call it as document.getelementbyid and it does what it sounds like it takes an id and it finds the matching element that contains or that has that id on it and it returns that object so if we go back to this simple example we could have any markup but the markup i have to keep it easy is from a couple videos ago it looks like this we have an h1 some paragraphs i've got a ul a form and i have an image that has an id bare dash photo let's add one more id let's do this paragraph here id equals um text no how about main sure so i have two ids on this page now i can select those elements using document dot get element by id so it's a method that exists on the document and i pass in an id as a string so i have bear photo that was one i'll try that and you can see what i get back it returns an element to me what's annoying i went over this a couple videos ago it prints it out as html which is not very useful but if we save it to a variable just to make it easier i'll call this image and then console.dir image we can see it's true object form as we talked about earlier here are all the properties i have so this selects based off of an id but it's not returning html to me even though it looks like it is it's returning an object and this object represents that one image with the id and if we scroll down we will see id is set to bare photo matching this id right there we also have properties like the type of the element tag name is set to image we could find the image source right here this is the image url so when we call document.getelementbyid pass in a string if there is a match and only if there's a match for that id we get that element back as an object the dom representation of that element this image remember you're only supposed to have one id on a page or one of each id so there shouldn't be multiple bare photos and if there were for some reason we still only get the first one that matches so we'll only ever get one element back and if we pass in an invalid id or something that's not on the page let's do document.getelementid of getelementbyid of bear in all caps we get nothing so no error we just get null because there isn't an element with that id and we'll do one more example we have something else with an id this paragraph the id is main if i select that id using document.getelementbyid main i'll save that to a variable called p we look at p it looks like it's html but remember it's actually an object console.dir p here is our object and it contains a lot of the similar properties a lot of the same methods as our image but different values for example we scroll down all the way down here we don't have a source attribute because it's not an image we have tag name set to p because it's a paragraph it's a p tag we have the text content lorem ipsum blah blah blah that's the content of this paragraph and there's a whole bunch of other things one other important topic that we'll see a couple times in this section is that this object here is of a particular type it is something called an html paragraph element if we look at our image do i still have it here let's do a console.dir image and we look at what type it is if you scroll down to the bottom it's called an html image element so they're both html elements but one is an image element one is a paragraph element now in this course we haven't talked about prototypes we haven't talked about constructor functions and classes so we won't go into much detail here but all you need to know is that there are different categories of elements on the page and some of them have their own type like an html paragraph element and an html image element every image element has a source for example a paragraph doesn't these are just different patterns for these objects so whenever we get an element by id or any of the other select methods we'll see in the next couple videos they return some sort of element to us it could be an image element it could be a paragraph element it could be something else we haven't seen yet and that's kind of it for document.getelementbyid so we call it on the document we pass in some id string and if there's a match we get that one element represented as an object if there's not a match we get null next up we have another method on the document to select elements but slightly different it's called get elements by tag name and once again it does what it sounds like rather than selecting by an id we select by a type of element i want all the images or the paragraphs or the h1s on a page so to use it it's exactly the same we do document dot and then the name of the method so instead of get element by id we want get elements with an s by tag name and that s is significant because we will get more than one element or potentially we could and that means that the elements returned are going to be stored in a list we're not going to get a single element back like we got from getelementbyid okay so let's try it what do we have on our page we've got a couple paragraphs we have a couple of inputs why don't we start with that let's get all the inputs so i pass in the name of the element as a string and there we go i'm getting three inputs returned it looks like an array it is not an array but we'll come back to that and if i look at each one of these elements once again they are dom objects we have an html input element this time instead of a paragraph element or an image element if we try the same thing with a different type like a p tag we now get the different paragraphs we have on our page so there we go we have two paragraphs the first one and the second one if i try it instead with uh what else do we have a bunch of lis on the page i get three lis each one is an object if i try it on an element that is not on the page uh like an h3 there are no h3s we get an empty collection back and if i instead try it on something where there's only one on the page like h1 we have one h1 on the page right here i still get a collection it just has one element in it so we don't get we don't ever get one element back on its own like we did with getelementbyid it returned the actual object not a collection but because we're getting multiple potentially we always get a collection back now let's talk about this collection what is this html collection it is an array-like object that is not an array so think of the arguments object that we saw a couple sections ago inside of a function every function has this arguments array-like object that is not actually an array it's a similar idea here this is a collection of objects it's called an html collection it is something that we it's a type in the dom it's a type of collection you get back frequently it is not an array but we can do some array-ish things so let's save one of these to a variable let's select the inputs so i'll just go back to this line save it to a variable const inputs and now i have my inputs variable let's clear this and let's try accessing the first input that works we can use array indices and brackets same syntax it looks like an array i can get the second element the third element and there is no element at index of three i can do inputs dot length and i do get a length but if i want to try using array methods like pop no luck same thing with push with includes with index of we really don't have much at our disposal in fact if we look at inputs and you just type dot in the dev tools here's what we've got we've got length we've got a couple methods these actually come from objects and nothing else so what what do we have here it's just a bare bones collection that allows us to access elements using indices and fortunately we can also iterate and that's it it's not supposed to be some useful data structure it's a very lightweight structure that stores elements so if you wanted to you could turn it into an array you could also just iterate over it like this let's do four let of inputs why don't we just console.log input for now there you go we're printing out each input remember this is not what they look like they're actual objects i hate that the browser does this chrome devtools i don't understand who why it just doesn't seem that useful to me most of the time we want to look at the object but maybe that's just because i'm a teacher and i need to show the objects who knows all right so we can iterate over them and since it's an iterable that means we can also use our friend spread so if i wanted to get these three inputs the inputs html collection it's not an array if i want to turn it into an array i can spread it into an array if you skip the videos on spread probably go back check those out so now i'll just call this array equals inputs if we look at array it's an actual array of those inputs but honestly at the end of the day a lot of the time what we end up doing is just looping over things and doing some sort of or making some sort of change to each input or each element that could be adding a style it could be reading its current value if this is a form a user clicks submit if we were using javascript we could intercept the form and get the values out what a user had typed in and then do something with them so we could select all inputs and then loop over the inputs and look at input.value we can actually try that right now if you want we'll just do console.log input.value and before i do that why don't i uh put some values in here so bear name we'll go with uh maxim [Music] maximus that's a good bear name i'll put a password in there just gibberish password and take a look we looped over all those inputs and i console.log input.value that is a property on each input element it has a value and i get maximus from the first one add from the second one and the third one is actually a button as well and that button does not have a value and if i look at inputs of two that last one it's that button type set to submit it does not have a value so that's just uh is what it is we don't get a value okay so let's get elements by tag name remember it returns this array-like object it's not an actual array but we can iterate over it each element in that array-like object is an element it's an actual object and it has a bunch of properties we can do things with it and when we call document.getelementsbytagname we pass in a string representing a tag name you pass in an invalid tag you won't get anything no error it's just not going to find anything with that type of tag name so we've seen get element by id we've seen get elements by tag name next we have another way of selecting next up a third way of selecting not by id not by tag name but by class name so we use a lot of classes traditionally in our markup so we can style them with css and if we want to select based off of those classes we have a special method to do just that document dot get elements it's plural again not singular like id get elements by class name and that s right there the pluralized s on elements tells us that we'll get a collection back we'll get multiple elements or we could get one element but it will be in a collection just like we had in the last video so what classes do i have i've got a class called special on two lis so i could use that and i think that's the only class i have maybe i'll add something to my h1 here let's go with class equals header okay and i will refresh my page to get that change now if i run document.getelementbyclassname of header we get that h1 notice it's in an html collection once again another array imposter it looks like an array but we don't get any of those array methods we could also select multiple so we have this class called special if we select using that class name we get two elements each one once again is an object has a bunch of stuff in it and if i select something that is not found like the class name of chickens nothing has that class name we get an empty collection if i try and select based off of an id we had an id called what do we have main it's not going to work there's nothing with the class name of main there's something with the id of main different methods different goals and that's pretty much it get elements by name does what it sounds like it's very similar to get elements by tag name except it uses a different criteria tag name versus class name we can iterate over it using a for loop you could use a regular for loop a four of loop one last thing i'll show you um it has to do with all of the methods we've seen so far is that you don't have to call them only on the document if i had a very complex document let's say with like thousands and thousands of elements if i wanted to select one element and then further search within that one element i could do that so here's an example let's say i have the class of special somewhere else on my page let's do it i don't know i'll just put it here i'll make a paragraph with the class of special and just put some stuff in there refresh my page if i want to search for elements with the class of special if i do document.getelementsbyclassname special i'm getting all three if i only want to get the elements with that class inside of this ul i can first select the ul so i can do that with get elements by tag name get elements by tag name and i want ul that gives me a list so i'm going to take the first one from that collection and save it to a variable called ul so now i have this variable ul which is an object and it has its own copy of get elements by class name or tag name so i could search within this ul and pass in special and now i only get those two allies that have the class of special because i narrowed it down i narrowed my search first to the ul i stored it in a variable and then i searched for special as a class within that ul versus earlier i looked for all elements in the document with that class and i got three so i could mix it up and you know use tag name again inside of the ul ul.get elements by tag name and then pass in li and i get the same thing and now i get three elements because there are three lis i'm not using class i'm looking for any li in the ul one very important note here is that getelementbyid does not work this way because ids are supposed to be unique across the entire document there should only be one element with whatever id bare photo there's no functionality to search within another element you don't need that you just search based off of the entire document so we don't have access to ul dot get element by id we only have well i mistyped it if i type get lmn you can see get elements by class name and by tag name we don't have id all right so you can window it down like that you can find one element save it to a variable search within that if you need to and that's it for these three basic ways of selecting get element by id get elements by class name get elements by tag name next we're going to see a whole new way of doing it a little bit of an improvement a nicer way of selecting where you only need one method so we just saw three different methods that we can use to select elements but there's actually a fourth method that rules them all it's called query selector and i put an image of a swiss army knife here because query selector is like the swiss army knife of dom selectors it can select everything that we used it can replicate the functionality of all of these selectors here we can select by an id or a tag name or a class name or many other criteria the way it works is that we pass in a css style selector so we can select a id using css where we pass in the hash symbol or a class we use a dot we can select an element just by writing the name of the element just like we do in css over here in my style sheet where are you here we are we're selecting by id we're selecting h1 so we're selecting by class we can select by attribute we can do the same thing using query selector so query selector has not been a thing from the get-go it hasn't been around as long as things like get element by id which is why the other ones exist because this one is so much more versatile query selector seems like it's all you would ever need and you can use it for everything it just hasn't been around as long but it is supported in all the modern browsers including internet explorer it does work there unlike a lot of other features that we wish would work and there are two versions of query selector what we're looking at here query selector and also query selector all which does the same thing except it returns a collection query selector this slide only returns a single element at most so let's try it out over here if we want to select the h1 on the page we could do document.queryselector h1 and we pass in the string h1 and we get that h1 right there if we wanted to select the paragraph the first paragraph we could do it this way but remember it only gives us the first match and there are two paragraphs on this page so we only get the first one i could also select the first input and this is essentially replicating get elements by tag name except we're getting the first match remember that get elements by tag name gives us a array like list versus query selector just gives us the first item the first match but we can do more complex things we could select by an id we have to use the hash sign in order to select an id just like we do when we're writing css so i have bear photo i think if i can remember yep that's our id for the image here i also had a different id what were you main we could select the second paragraph by using hash and then main so this is just like document.getelementbyid main but here we don't say it's an id we just pass in a string it's assumed it's an id when we use query selector we have to be more specific we pass in the css style selector so i'm getting the same paragraph now what does query selector actually return to us why don't we save both of those to a variable so the first one i'll save to a variable called main one and then the second one where we use getelementbyid i'll save to main two i'll clear my screen and then let's do the annoying console.dir main one open it up it looks like an object it is an object it's an html paragraph element let's do the same thing for main two looks like an object scroll down it is an object and it's also an html paragraph element alright so they both give us the same thing in this case it's just two different ways of selecting we can also select by class if i wanted to select these elements i can only pick one remember but this class is used in three different places it's called what is it special so i can do a document.query selector of the id special where i need to use a period to signify it's an id so that gives me the first match this paragraph here but because i can pass in a css selector i can get more complex i can say the first li with the class of special and this is just valid css so this is no new syntax assuming that you have some experience with css and that's why i did that whole video about making sure you're cool with html and css anyway let's go ahead and try something a little more complex i'll add in a second ul with a couple allies but instead of doing it just out in the open inside the body i'll come down to the end and add in another ul but i'll put it inside of a section tag and then i'll have my ul and a couple allies i'll do vegetables i guess carrots uh peas and broccoli broccoli is there two c's in that yeah i think so i don't know if i'm wrong i'm really sorry okay so i've got those in there let's give peas the class of special as well so if i want to select this li right here using query selector i need to refresh my page and i want to select that li right there with query selector it's not going to work just by selecting the class of special because we're getting the first special which is up here and it's not going to work to say li with the class of special because we have this first one that has an li or it is an li with the class of special so how could i get more specific well this one is located inside of a section tag so i could do this this is valid css section li dot special i could even get more specific it won't make a difference here but it's also nested in a ul inside of a section so this is saying find me a list item with the class of special that is nested somewhere in a ul that is itself nested somewhere in a section tag i mean i could even do this if i really wanted to body and get extra specific so that's another variation of query selector that's just a valid css selector syntax we can also select based off of attributes so if i want to get this password input right now if i do document.queryselector of input you know what will happen we have multiple inputs we only get the first one which is right here type set to text if i want that second one i can do input where type equals and then password so this is using the css attribute selector syntax and now i get that input and we saw this syntax a couple videos ago with css we did the same thing it's the identical selector we just moved it into a javascript string and passed it into query selector so we're not styling anything using this we're purely selecting all right so we've seen that query selector is pretty powerful we can get a lot more specific we can even ignoring that ignoring the fact that we can get more specific and detailed we can use query selector in place of all those other methods we saw and then we have query selector all which uses the exact same syntax except it returns to us a collection so not just the first result so if i do document.queryselector of input i get the first input if i do query selector all i get all inputs that match and there's three of them if i did document.queryselectorall dot uh let's do the class of special we have four items the paragraph with special and then the three lis if i do li we get six of them because there's six total allies on this page if i do something like the id of uh did we have one called main i think so one this paragraph or this paragraph is the idea of main we still get a collection just with one item in it notice something kind of odd this result that we're getting back is a node list but when we do document dot let's do get elements by tag name elements by tag name of allies we get an html collection here we got something called a node list so what is a node list it's another type of a collection you don't need to worry about it too much here but if we look at what the node list contains this paragraph is still an html paragraph element it's just put in a different container from query selector all that's how it works a node list is another array-like object and if we play around with it we can save it to a variable so let's get all of the which one should we do let's save all of the special class elements to a variable we'll call it specials and i'll clear my console make some more room so we have specials it is an array like object so i can do specials of zero i can do specials.length and then if we do specials dot and then look at what else we have there's really not much else but we do have four each so this was not available to us with a html collection it is available with a node list but don't get bogged down don't worry about it honestly it's not a big deal at this point i just wanted to highlight that there is a slight difference they're not the exact same type the not they're not the exact same collection that we get back or the container is different both of them are fake lightweight versions of arrays so that is one difference when you use query selector and also another difference to know about query selector is that it is a little less performant it's really not a big deal for the stuff we're doing but as you can imagine depending on the selector you pass in it could have to do a lot of work compared to some of these older versions like get element by id or get elements by tag name generally those are a little bit more optimized or a little faster but i definitely definitely would recommend you go with query selector and it's not a good enough reason it's not a good enough difference to not use or to avoid query selector alright so query selector query selector all very useful it's what i'll be using for most of the course here because we can get more specific but also it's just nice to use one method and not have to worry about those other methods you pass in a css selector as a string and you get back either the first match if you're using query selector or you get back a collection of all matches if you use query selector all
Info
Channel: Code With Sahib
Views: 1,413
Rating: undefined out of 5
Keywords: JS In the Browser - DOM Manipulation, javascript dom crash course, js dom, simple javascript, add classes in javascript, todo list javascript, queryselector in javascript, innerhtml, textcontent, javascript dom methods, javascript getElementById, javascript getElementsByClassName, javascript getElementsByTagName, javascript dom targeting methods, javascript find html elements tutorial, javascript document methods
Id: PwijaO3za_o
Channel Id: undefined
Length: 72min 28sec (4348 seconds)
Published: Sat Sep 12 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.