I want to add classes named like those in data array (categories) to each boxes in sequence (in container). For example, first box except "box" class should have: "highlighted" "special-header" "important" classes. I tried to do it like this, but it doesn't work:
var boxes = document.querySelectorAll('.box');
for (var i = 0; i < boxes.length; i++) {
//Add classes to all boxes
var categories = data[i].categories;
boxes[i].classList.add(categories)
}
I feel that it has to be something with forEach() or with another loop refers to categories array. How to refer to each element in "categories" separately?
var data = [{
id: 'box1',
title: 'First box',
content: '<p>Lorem ipsum dolor sit amet!</p>',
categories: ['highlighted', 'special-header', 'important']
},
{
id: 'box2',
title: 'Second box',
content: '<p>Lorem ipsum dolor sit amet!</p>',
categories: ['special-header', 'important']
},
{
id: 'box3',
title: 'Third box',
content: '<p>Lorem ipsum dolor sit amet!</p>',
categories: ['highlighted', 'important']
},
{
id: 'box4',
title: 'Fourth box',
content: '<p>Lorem ipsum dolor sit amet!</p>',
categories: ['highlighted']
},
{
id: 'box5',
title: 'Fifth box',
content: '<p>Lorem ipsum dolor sit amet!</p>',
categories: []
},
];
var boxes = document.querySelectorAll('.box');
for (var i = 0; i < boxes.length; i++) {
//Add classes to all boxes
var categories = data[i].categories;
boxes[i].classList.add(categories)
}
<div class="container">
<div class="box">
<header></header>
<p></p>
</div>
<div class="box">
<header></header>
<p></p>
</div>
<div class="box">
<header></header>
<p></p>
</div>
<div class="box">
<header></header>
<p></p>
</div>
<div class="box">
<header></header>
<p></p>
</div>
</div>