Change a paragraph's background color in JavaScript
Beginner · 3 min read
Highlighting a row you just saved, marking a wrong answer in red, flashing a warning: all of these come down to changing an element's background color from JavaScript. Setting it takes one line. Reading it back is where people get surprised, so this lesson covers both.
In this tutorial you will write a small function that sets a paragraph's background color, clears it again, and then find out why JavaScript sometimes says an element has no color when you can see that it does. You need to know basic HTML and CSS.
Two places a style can come from
An element can get its look from two places:
- A stylesheet: a CSS rule like
#styled { background-color: #eaf6ef; }. - An inline style: a value set on the element itself, either with a
style="..."attribute or from JavaScript.
element.style in JavaScript is the inline style only. That one fact explains most of this exercise.
Here is the page:
<p id="para">This paragraph gets a background.</p>
<p id="styled" class="tinted">Coloured by a stylesheet.</p>
The second paragraph is tinted by a CSS rule for the class tinted. The first has no color yet.
CSS names in JavaScript
In CSS the property is background-color. JavaScript can't use a hyphen in a name, so it becomes backgroundColor: drop the hyphen, capitalize the next letter.
Here is the exercise. Try it yourself first if you like, or read on.
3 Set a paragraph’s background colour
easySet the background colour of a paragraph. Then look at what a browser gives back when you read the value.
Stuck? Three hints, smallest first
- 1.
background-colorbecomesstyle.backgroundColor. - 2. The
styleproperty reflects inline styles only, not what a stylesheet applied. - 3.
getComputedStyleis the way to read the value a stylesheet set.
Step 1: set the background
A function that takes an element and a color keeps this reusable:
const para = document.getElementById('para');
const setBackground = (element, colour) => {
element.style.backgroundColor = colour;
};
setBackground(para, '#fdefec');
console.log(para.textContent); // This paragraph gets a background.
The paragraph turns pale pink, and its text is untouched. Any CSS color works as the value: 'red', '#fdefec', 'rgb(253, 239, 236)'.
If you read para.style.backgroundColor back now, a browser usually gives you rgb(253, 239, 236), not the hex you wrote. It stores colors in its own format. So don't test a color with === '#fdefec'; that comparison can fail even though the color is right.
Step 2: clear it again
To remove an inline style, set it to an empty string:
const para = document.getElementById('para');
para.style.backgroundColor = '#fdefec';
para.style.backgroundColor = '';
console.log(para.style.backgroundColor === ''); // true
The paragraph goes back to whatever the stylesheet says, which here is no background at all. Setting null or using delete on the property is unreliable across browsers. The empty string is the one that always works.
Step 3: the stylesheet color you can't see
Now look at the second paragraph, the one the stylesheet colors:
const styled = document.getElementById('styled');
console.log(styled.classList.contains('tinted')); // true
console.log(styled.style.backgroundColor); // an empty string
The paragraph is visibly green on the page, but style.backgroundColor is empty. That isn't a bug. The color comes from the stylesheet, and .style only knows about inline styles.
Step 4: read what the browser actually applied
To ask "what color is this element really?", use getComputedStyle. It combines the stylesheet, inline styles and the browser's defaults, and gives you the final result:
const styled = document.getElementById('styled');
console.log(getComputedStyle(styled).backgroundColor); // rgb(234, 246, 239)
That is #eaf6ef written as rgb(). getComputedStyle is for reading only. To change a style, keep using element.style. The live demo on this page prints all three readings side by side when you press its button.
The full solution
The panel sets the background, clears it, sets it again, and checks the stylesheet-colored paragraph has nothing in its .style. Press Run to see the output, then press the button in the live demo to compare with a real browser.
allow-scripts only, so it cannot reach this page.const para = el('p', { id: 'para' }, 'This paragraph gets a background.');
const fromSheet = el('p', { id: 'styled', class: 'tinted' }, 'Coloured by a stylesheet.');
document.body.appendChild(para);
document.body.appendChild(fromSheet);
const setBackground = (element, colour) => {
element.style.backgroundColor = colour;
};
console.log('before:', JSON.stringify(para.style.backgroundColor));
setBackground(para, '#fdefec');
console.log('after :', JSON.stringify(para.style.backgroundColor));
// The element coloured by a stylesheet has NOTHING in its style property.
// .style is inline styles only. This is the single most common surprise here.
console.log('coloured by a stylesheet, read via .style:', JSON.stringify(fromSheet.style.backgroundColor));
console.log('<- empty, even though it is visibly tinted. Use getComputedStyle.');
// Removing an inline style: set it to '' rather than deleting the property.
setBackground(para, '');
console.log('after clearing:', JSON.stringify(para.style.backgroundColor));
setBackground(para, '#fdefec');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('nothing inline to begin with', fromSheet.style.backgroundColor, undefined);
test('the background is set', para.style.backgroundColor, '#fdefec');
test('the text is untouched', para.textContent, 'This paragraph gets a background.');
test('a stylesheet colour does NOT appear in .style', fromSheet.style.backgroundColor, undefined);
test('even though the class is there', fromSheet.classList.contains('tinted'), true);
test('so .style tells you about inline styles only', Object.keys(fromSheet.style).length, 0);
test('clearing with an empty string works', (() => { setBackground(para, ''); return para.style.backgroundColor; })(), '');
test('and it can be set again', (() => { setBackground(para, 'red'); return para.style.backgroundColor; })(), 'red');
test('a named colour is stored as written', para.style.backgroundColor, 'red');
test('setting background is not the same property as color', para.style.color, undefined);
element.style is inline styles only. An element coloured by a stylesheet has an empty style.backgroundColor, which the assertions above confirm — this is why "I set it in CSS but JavaScript says it is empty" comes up so often. getComputedStyle(el).backgroundColor is the read path, and note it returns the browser's normalised form (rgb(253, 239, 236)), not the hex you wrote. The live demo prints all three values side by side.
To remove an inline style, assign ''. Assigning null or using delete is unreliable across browsers.
Common mistakes
- Writing
style.background-color. JavaScript reads that asstyle.background - color, a subtraction. UsebackgroundColor. - Expecting
.styleto show stylesheet colors. It only shows inline styles. UsegetComputedStyle(el)to read the final value. - Comparing colors as hex strings. Browsers hand colors back as
rgb(...), so=== '#fdefec'can be false even when the color is right.
Try it yourself
- Add a button that switches the first paragraph between
'#fdefec'and no background each time it is clicked. - Use
getComputedStyleto read the first paragraph'scolor(the text color). You never set it, so where does the value come from? - Instead of setting the color inline, add a class with
classList.add('tinted'). Which approach keeps your colors in one file?