Current section: Hello World in JS 59 exercises
solution

Generate the Root Node

Loading solution

Transcript

00:00 Alright, so we're going to delete this element and if I save that we get a reload and this is No longer working. We're getting a type error cannot read properties of null reading append So what's happening here is this root element could be an HTML element or it could be null because maybe there is no

00:17 Element called root in the DOM which is the case now because we don't have that element in our DOM anymore So instead of getting the element what we're going to do is create the element So we're going to say document dot create element. It'll be a div and

00:33 If we want to we can say root element dot ID equals root just for the fun of it We don't really need to but we're just exploring the DOM right now. No, no problem save that and now we're no longer getting error But we're also not getting anything in the DOM because again we created this in memory. It's sitting out there in memory

00:52 It may have an element that is appended to it, but it's not in the DOM right now And so we've got to say document dot body append root element So we've appended our element our hello world element to the root and now we're appending the root to the body Save that and we get our hello world

01:11 We've also got our root right there and you'll notice actually something kind of interesting from what we had before the root was Right up here before But now with our changes that actually goes down here and that's because of append if we really wanted the position to be exact we could say prepend and

01:30 Now it's going to go at the beginning, but it doesn't really make a difference In any case, so I'm fine with append. But yeah, hopefully that gave you a little bit More of an exploration of what you can do with the DOM There's a there's an entire world there and we're not going to go that much deeper into it

01:49 But I think it's useful for you to understand that we're creating elements. We're appending elements We're modifying element properties and that is how you make a dynamic web application We could of course add buttons and event handlers and all that stuff We're not going to go that deep into the DOM feel free to dive into that if you're interested

02:08 But this is how you create elements using JavaScript