-
Okay, now you know how to change
the contents of an element
-
and the values of its attributes.
-
What else is left? Well, what if
we wanted to change its style?
-
Normally, we would do that in CSS,
but there are some times when we
-
want to do that in JavaScript, like when
we want to animate styles over time or
-
change them after a user clicks something,
which we'll see how to do soon, I promise.
-
Let's change the style of this heading.
-
If we did that in CSS,
it would look like this--
-
`#heading` to select by ID,
and then we'll say `color: orange`.
-
Ta da, it's orange, just like the cat.
-
Now, to do that in JavaScript,
-
we first find the heading element,
which we have here.
-
Then, we're going to access
its style attribute with `.style`.
-
Then, we access the property
that we're interested in-- `color`--
-
and set it equal to the new value.
-
Let's delete the property in CSS to
see if it worked. Yup, it worked.
-
Now, notice down here we've got two dots
because we're actually accessing
-
two objects. One of them is the element
object and the other is the style object
-
that contains all the styles for that
element as different properties.
-
What if we also wanted to change the
background color of that heading?
-
In CSS it would be
`background-color: black;`
-
Let's try that in JavaScript. So
-
`headingEl.style.background-color
= "black";`
-
Uh oh, we have an error.
This is actually invalid JavaScript,
-
because property names
can't contain hyphens.
-
Instead we need to convert this CSS
property name to a form that's valid
-
JavaScript, which we do by camel-casing it.
Remove the hyphen and capitalize the "c".
-
And let's go test it out by deleting this property here, and yep, it's still black.
-
Now that I'm getting fancy, I want
to make the heading center aligned too.
-
So I will add one more line down here.
-
`headingEl.style.textAlign`--
which we camel-case-- `= "center"`.
-
Once again, we camel-case it since it
was two words with a hyphen before,
-
and now we've got this heading that looks
like our cat and also like Halloween. Yay.