Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript backgroundColor = 'none' or null is more efficient?

I’ve seen many implementations where the backgroundColor is being set on .js script file using:
document.getElementById("elementId").style.backgroundColor = 'none';

I’ve also seen other implementations for basically the same purpose, using:
document.getElementById("elementId").style.backgroundColor = null;

What is really the difference or what is the most recommended approach between ‘none’ and null for setting the backgroundColor in the script file?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tested both approaches and I don’t really see any visible difference considering a very basic use case.

>Solution :

First, 'none' is not a valid value for the background-color CSS property, although it is valid for the background property.

Setting .style.background = 'none' or .style.backgroundColor = 'unset' can remove the previously set background color on the element, regardless of where the background color for the element was originally set (either external stylesheet, internal stylesheet, or inline style).

Setting .style.backgroundColor = null is like setting the value to an empty string. It only wipes out the previously set inline background-color property, if there was one. It has no effect on the styling from external or internal stylesheets.

// try to remove all the background colors
const divs = document.querySelectorAll('div');
divs[0].style.backgroundColor = divs[1].style.backgroundColor = null;
divs[2].style.background = 'none';
.blue {
  background-color: dodgerblue;
}
<div class="blue">Background color set from internal stylesheet (tried to remove background with <code>backgroundColor = null</code>)</div>
<div style="background-color: red;">Background color set with inline style (background removed with <code>backgroundColor = null</code>)</div>
<div class="blue">Background color set from internal stylesheet (background removed with <code>background = 'none'</code>)</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading