This can be done, but not the way you are doing it. You'll need to pass (as an index, using bracket notation) the CSS property name (a string) into the object returned by accessing the .style
property.
Also, don't use .getElementsByTagName()
as it's a 25+ year old API that returns a "live" node list, which can hurt performance. Instead, use .querySelectorAll()
and loop over the returned collection with the Array.forEach()
method, which is an alternative to a traditional for
counting loop that is a bit easier to work with since you don't have to manage any loop counters and get direct access to the element you are iterating.
var allElements = document.querySelectorAll('*');
var tag = 'backgroundColor'; // Just store the name of the CSS property
var val = 'black';
// Use the more modern Array.forEach() method of looping
allElements.forEach(function(element){
element.style[tag] = val; // Pass the style object's property name as an index
});
* { color:white; border:2px solid white; }
<div>This is a div<br>that spans two lines.<div>
<p>Here's a paragraph</p>
<h1>And a Heading 1</h1>