Changing DOM elements
Viewers: in countries Watching now:
- Creating variables, functions, and loops
- Writing conditional code
- Sending messages to the console
- Working with different variable types and objects
- Creating and changing DOM objects
- Event handling
- Working with timers
- Building smarter forms
- Using regular expressions
Changing DOM elements
So that's what comes first. Step two is okay, then we can change it. The question is, what do you want to change about it? If you were manually editing this code in a text editor, what would you want to do? Do you want to pick an attribute and change it or add a new attribute? Do you want to change a link inside a heading? Do you want to add a whole bunch of new elements inside a div or inside a list? Well, we can do all of that, but let's talk about changing existing elements, rather than creating new ones.
We pass in a value. So we call the setAttribute method. We pass it the name in quotes. We pass it the value in quotes, always as a string. If the attribute doesn't currently exist, it will be created. Let's take a look at this. So I have a simple HTML page that I have here. There's nothing remarkable about it. It's just to have something to work with. You could work with a test page yourself. I have that open in my editor here, and down at the bottom, I have a link to my script.js file, which is in the same folder, which is actually over here.
I'm now going to uncomment just a console.log message and ask for mainTitle's innerHTML property, save that, jump back over, and I'll refresh this page. You need to have Firebug open to see that. The console.log message is writing out Welcome to Explore California! So in this case, innerHTML of this anchor tag is giving us the text inside it. When you have a very simple tag, innerHTML can be a good way to work with it.
A simple h1 is fine, as is an a tag, as is even there's a paragraph. Grabbing, for example, a div might give you a little more. Let's say we get a div that contains quite a few things, like this div ID of sidebar. If I do exactly the same kind of thing here, let's just change that and call it a var sidebar, and log out its innerHTML, jump back over to Firefox, and refresh the page, well, you see what we're getting here is the entire contents of that div and all its divs inside it and all its h2s.