简体   繁体   中英

Is there any way to set a style for a DOM object with a variable?

I have here some code, in which I am trying to change all of something on a page.

var allElements = document.getElementsByTagName('*');

var tag = '.style.backgroundColor';
var val = 'black';

for (var i = 0; i < allElements.length;i++) {
  allElements[i] + tag = val;
}

How can I make this work?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM