Accessing HTML and CSS in JavaScript

slides

See the Pen 5.3 Accessing HTML and CSS in JavaScript by LSU DDEM (@lsuddem) on CodePen.

Accessing HTML and CSS in Javascript

document.getElementById()

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" 

In this example, the text in the header will change to “New Text”.

Practice in Codepen

See the Pen 5.3 Practice by LSU DDEM (@lsuddem) on CodePen.

document.getElementsByTagName()

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);

Console View:

Image description

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";

Example in Codepen

See the Pen Untitled by LSU DDEM (@lsuddem) on CodePen.

Accessing CSS in JavaScript

In order to change CSS styling in JavaScript, we first need to access the HTML element that we want to style, then, we add the style property, which specifies that we’re accessing CSS. Next, we add whatever property we want to change, for example color. Here is an example:

<h1 id="h1"> My Header </h1>
<p id="para1"> My Paragraph </p>
document.getElementById("para1").style.color = "green";

Notice that in CSS, we put the name of the color without quotes, but in JavaScript, we need to use quotes to make the color a string.

We can also use variables to store elements, and then change their style properties:

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"

Exercise 5.3

See the Pen Exercise 5.3 by LSU DDEM (@lsuddem) on CodePen.