1

I have a list that I want to give a metal/metallic background for each item in the list using DOM manipulation.

List using Bootstrap 4

 <ul id="items" class="list-group">
   <li class="list-group-item">Item 1</li>
   <li class="list-group-item">Item 2</li>
   <li class="list-group-item">Item 3</li>
   <li class="list-group-item">Item 4</li>
 </ul>

This is my attempt to style the background of the class.

var backGroundMetallic = document.getElementsByClassName("list-group");

for(var i = 0; i < backGroundMetallic.length; i++) {
  backGroundMetallic[i].style.backgroundColor = '#7fffd4';
}

I'm only able to put use one CSS color. Is there a way to reference a CSS class so I can use more than one style in order to style the background for the list to achieve making it metal/metallic?

Intervalia
  • 10,248
  • 2
  • 30
  • 60
  • Try `var backGroundMetallic = document.getElementsByClassName("list-group-item");` – Esger May 07 '19 at 20:13
  • 3
    What does "metal/metallic" mean to you? Show some examples of what you want. Also, why DOM manipulation? CSS is much more efficient. – Heretic Monkey May 07 '19 at 20:13
  • are you trying to add a background gradient then check this https://stackoverflow.com/questions/15071062/using-javascript-to-edit-css-gradient – dota2pro May 07 '19 at 20:15
  • You could use a linear gradient effect to make the background look metallic.Try playing around with the Gradient Generator at https://www.cssmatic.com. – Nosnetrom May 07 '19 at 20:15
  • 1
    This isn't "DOM Manipulation". Styling has next to nothing to do with the DOM. – Rob May 07 '19 at 20:15
  • 1
    I can't see how is using JavaScript relevant in such case. – Quentin Veron May 07 '19 at 20:15

3 Answers3

1

To add a CSS class to an element, you can use .classList.add():

var backGroundMetallic = document.getElementsByClassName("list-group");

for(var i = 0; i < backGroundMetallic.length; i++){
    backGroundMetallic[i].classList.add("metallic");
}

The same functionallity in one line:

document.querySelectorAll(".list-group")
  .forEach(el => el.classList.add("metallic"))

And define the class:

.metallic{
  background-color: #7fffd4;
}
Community
  • 1
  • 1
FZs
  • 16,581
  • 13
  • 41
  • 50
0

Either put all the styles in a class and do

backGroundMetallic[i].classList.add(classname);

or do

backGroundMetallic[i].setAttribute("style", "color: red; background-color: black;");
Rahul Vala
  • 695
  • 8
  • 17
0

You can try this code and custom the linear-gradient as you want:

for(var i = 0; i < backGroundMetallic.length; i++) {
  backGroundMetallic[i].setAttribute('style','background-color : #e7eff9;background-image : linear-gradient(315deg, #e7eff9 0%, #cfd6e6 74%);');
}
Conan
  • 319
  • 2
  • 9