Martin Martin - 7 months ago 8
HTML Question

How to set class name for created divs

For example, I've created a list of

div
elements and I want to set a
class name
only for 1st, 3rd and 4th elements of this list. Is it possible?

I've tried to use
setAttribute
but got nothing.

What am I doing wrong?



var newsListData = [
{

"title" : "title",


},
{

"title" : "title",

},
{

"title" : 'title',

},
{

"title" : 'title',

}]



window.onload=function(index){
var divList;
for (var i = 0; i < newsListData.length; i++){
divList = document.createElement("div");
divList.innerHTML = newsListData[i].title;
document.getElementsByClassName("list")[0].appendChild(divList);
divList[0].setAttribute("class", "sample"); // stuck here
}

}

.sample {
color : red;
}

<div class="list">

</div>




Answer

Is this what you're looking for?

window.onload=function(index){
    var divList;
    for (var i = 0; i < newsListData.length; i++){
    divList = document.createElement("div");
    divList.innerHTML = newsListData[i].title;
    document.getElementsByClassName("list")[0].appendChild(divList);
    divList.setAttribute("class", "sample"); // stuck here

  }
  var second = document.getElementsByClassName('sample')[1];
  second.setAttribute("class", "");
}