-1

I am trying to add a class to a list of classes. I have tried using

document.getElementById('sectionRowTitles').className += "sectionFieldRating"

as well as

document.getElementById('sectionRowTitles').setAttribute("class", document.getElementById('sectionRowTitles').getAttribute("class") + "sectionFieldRating")

and also

var sectionFieldRating = document.createElement('div');
document.getElementById('sectionRowTitles').appendChild('sectionFieldRating');

The HTML looks like

<div class="sectionRow" id="sectionRowTitles">
    <div class="sectionFieldCourse column">Course</div>
    <div class="sectionFieldInstructor column">Instructor</div>
    <div class="sectionFieldMethod column">Method</div>
</div>
Makyen
  • 31,849
  • 12
  • 86
  • 121
  • 1
    you had it in the title but not in the code.. – I wrestled a bear once. Oct 19 '16 at 18:33
  • You have not explained what the problem is that you are having. In other words, what *exactly* is happening that you did not expect? What did you expect to happen? There are obvious issues with what you have shown, but they may not be the issue you are attempting to address, as you have not described what you issue is. As stated, this appears to have nothing, specifically, to do with Chrome Extensions. – Makyen Oct 19 '16 at 19:02
  • You are directly manipulating the list of classes. The `class` attribute is a *space separated* list. You are trying to add a class without separating it from any other already existing class(es) with a space. Doing so will result in both your new class and the last class in the list not working the way you are expecting. Making this manipulation easier is why [`Element.classList`](https://developer.mozilla.org/en/docs/Web/API/Element/classList) exists. Given that you are developing this for a Chrome extension, there is no need to be compatible with anything other than Chrome. Thus, use it. – Makyen Oct 19 '16 at 19:09
  • Possible duplicate of [Change an element's class with JavaScript](http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript) – Makyen Oct 19 '16 at 19:10

2 Answers2

2

You can use classList:

document.getElementById('sectionRowTitles').classList.add("sectionFieldRating");

classList is available in all modern browsers and IE10+.

joews
  • 29,767
  • 10
  • 79
  • 91
0

classlist is available on all modern browsers, if for some reason you're coding for ancient browsers you can use..

el.setAttribute("class", el.getAttribute("class")+" "+newclass)

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116