Until recently, I’d never gotten to play around with it much. I had such a good time, I wanted to share a bit of what I learned. Don’t let JS intimidate you! I avoided front-end web development for a long time because I assumed the amount of information I needed to be productive was just vast and prohibitive. Turns out the basics aren’t too bad at all.
This will make the most sense if you have some understanding of HTML. Here’s a quick refresher:
A class is a means of categorizing or grouping your tags. Once your tags are grouped this way, it’s easy to perform similar operations on several tags at once.
By contrast, an id is a unique identifier for a tag. Using an id will let you grab a particular tag whenever you need it. This is handy for, say, populating data into particular fields.
Let’s try it out
We’re going to need two files. Try remixing this Glitch project!
Here's what's going in index.html:
That’s a simple shell of a page. It will look something like this:
<script src="/script.js" defer></script>
This tag tells the browser how to access the script you want. defer asks the browser not to execute the script until after the complete page has been loaded. This ensures that everything it’s expecting on the page exists when it starts.
And that’s about it for the HTML. Now, the good bits.
Modifying existing elements
Let’s modify the header. Start by adding this to script.js:
var header = document.getElementById("header");
document.getElementById() grabs our header tag and stores it to the header variable. Once we have a grip on the header, it’s easy to reset its content. Add this line:
Load index.html (on Glitch, click “Show”) and you’ll be greeted by your garish new text:
- document.getElementsByTagName() returns an array of all tags of a given name. If you want to act upon all links (a), you could do that this way.
- document.getElementsByClassName() will give you an array of all tags of a given class.
Creating new elements
Let’s grab the body tag…
var bodyTag = document.body;
And append our new paragraph text:
When we check out our page, it should look like this:
Pretty cool, huh? With just a few functions, you have enough to build dynamic, script-driven web pages. Here’s a link to a Glitch project with the finished code, for your reference.
Have fun with your new tools!