document.getElementById() is used to access an element by its id name.
For this method, we DO NOT use the hash sign (#), because JavaScript already knows that it is looking for an id. So if we have an element, like this:
<h1 id="header1">This is my Header</h1>
We could access it in javascript like this:
let myHeader = document.getElementById("header1");
myHeader.innerHTML = "New Text"
See the Pen 5.3 Practice by LSU DDEM (@lsuddem) on CodePen.
The getElementsByTagName() method returns a HTML collection of all elements with a specified tag name.
A collection is an array-like list of HTML elements.
Let’s look at an example
<p>My Paragraph</p>
<p>My Second Paragraph</p>
<p>My Third Paragraph</p>
let myTags = document.getElementsByTagName("p");
console.log(myTags);
We can see that we get an object-like list, which is ordered by number.
Because our list is in numerical order, we can access each element by using square brackets, similar to accessing elements of an array, so if we want to change the text in the first paragraph element, we could add the following code:
myTags[0].innerHTML = "This is the first paragraph";
//Or to change the text in the second paragraph, uncomment the following code:
myTags[1].innerHTML = "This is the second paragraph";
<h1 id="h1"> My Header </h1>
<p id="para1"> My Paragraph </p>
document.getElementById("para1").style.color = "green";
let header = document.getElementById("h1");
header.style.color = "orange"
In CSS, we use dashes inbetween words for different properties, for example background-color, or font-size. JavaScript does not recognize dashes in properties, so in JavaScript, we use camelCase, so backgroundColor or fontSize.
So if we wanted to change the background color of the body, we would do it like this:
document.body.style.backgroundColor = "violet"
See the Pen Exercise 5.3 by LSU DDEM (@lsuddem) on CodePen.