Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  81] [ 4]  / answers: 1 / hits: 5272  / 3 Years ago, wed, april 14, 2021, 12:00:00

I have these different div elements with classes such as red or green.


<div class="sidebar">
<div class="color_box red"></div>
<div class="color_box orange"></div>
<div class="color_box yellow"></div>
<div class="color_box green"></div>
<div class="color_box blue"></div>
<div class="color_box purple"></div>
<div class="color_box black"></div>
<div class="color_box white"></div>
</div>

I want to set the background color of the div element to its class name. So if the class name is red, I would want the div background to be red. I'm not sure if I need to add javascript or something else. I've looked at this and it was not what I wanted at all.


Thank you in advance!


More From » html

 Answers
1

A solution that is dynamic and does not depend on class names is the use of a custom data attribute.


Take a look at the following solution:




<div class=sidebar>
<div data-backgroundcolor=red class=color_box>BOX</div>
<div data-backgroundcolor=orange class=color_box>BOX</div>
<div data-backgroundcolor=yellow class=color_box>BOX</div>
<div data-backgroundcolor=green class=color_box>BOX</div>
<div data-backgroundcolor=blue class=color_box>BOX</div>
<div data-backgroundcolor=purple class=color_box>BOX</div>
<div data-backgroundcolor=black class=color_box>BOX</div>
<div data-backgroundcolor=white class=color_box>BOX</div>
</div>

<script>
const colorboxes = document.querySelectorAll('.color_box');
colorboxes.forEach(el => {
el.style.backgroundColor = el.dataset.backgroundcolor
})
</script>




[#1474] Thursday, April 8, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anthonyw

Total Points: 589
Total Questions: 117
Total Answers: 117

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
anthonyw questions
;