The document is the webpage and all of the objects contained therein.
// try pasting any of these commands into the console to get a quick sample of selecting objects in the document document.URL; document.head; document.body; document.links;
Let’s start with the 5 basic methods for selecting individual objects in the document
// here are 5 methods for selecting specific objects in the document document.getElementById() document.getElementsByClassName() document.getElementsByTagName() document.querySelector() document.querySelectorAll()
Selects a single element with an ID that you have to name. Because there can only be one object with a specific ID on a page, this will only ever select 1 element. For example if we have an h1 with id “blogtitle”
<h1 id="blogtitle">Why Dogs Rule and Cats Drool</h1>
you would select this specific h1 with:
var blogTitle = document.getElementByID("blogtitle");
Selects all elements of a specific class. For example if we have a bunch of
- items with class “todo”.
<ul class="todo"> Wash the Car </ul> <ul class="todo"> Walk the Dog </ul> <ul class="todo"> Finish Homework </ul>
we can select all of them with:
var toDo = document.getElementsByClassName("todo");
Just like the previous method except it selects all objects with the chosen HTML tag. Examples of html tags would be, h1, p, li, div etc etc…
var listItems = document.getElementsByTagName("li");
querySelector is a little bit different. It is a new method, and instead of specifying what type of item you are selecting with the method, you specify it in the argument, so an id would be selected with #id and a class with .class. So to match the previous two examples we would have:
var blogTitle = document.querySelector("#blogtitle"); var toDo = document.querySelector(".todo");
NOTE that .querySelector() will only select the FIRST item that matches. To select all matching items you would use .querySelectorAll()
Just like the previous except that it will select all items that match, not just the first.