0

Recently I encountered this:

If in the JS:22 line I add this.classlist.add("active"); then it should change the color according to the CSS class, but it does not work. Any idea?

var newItem = 1;

var ourList = document.getElementById("test_id");

var ourButton = document.getElementById("Button_id");

var test_function = document.getElementById("Headline");

var OurListID = document.getElementById("test_id").getElementsByTagName('li')




for (i = 0; i < OurListID.length; i++) {
 OurListID[i].addEventListener("click", activateItem );
}



function activateItem () {
    test_function.innerHTML = this.innerHTML;
   this.classlist.add("active");
    
}



ourButton.addEventListener("click", NewFunctionName );

 function NewFunctionName () {
  test_id.innerHTML += "<li>Something New " + newItem + "</li>";
  newItem++;
 }


/** JavaScriptGenius: 19 min 23 sec - continue **/
.active {                                     
     background-color: blue;
}
<!Doctype html>
<html>
<head>
<title>Take me to the paradise city</title>

</head>

<link rel="stylesheet" type="text/css" href="style.css">

<body>
<h1 id="Headline">Test Headline</h1>
  <p id="IDTest">Click a list item to replace this text.</p>

  <button id="Button_id">Add new item</button>
<div>
  <ul id="test_id">
    <li>First item</li>
    <li>Second item</li>
    <li>Third item</li>
    <li>Fourth item</li>
  </ul>
</div>
<div>
    <p>JavaScript Test page</p>
</div>

<script src="JavaScriptGenius.js"></script>
</body>
</html>
htshame
  • 6,599
  • 5
  • 36
  • 56
  • 1
    It’s `classList`, not `classlist`. Also, when you [overwrite `innerHTML` all your event listeners get lost](https://stackoverflow.com/questions/5113105/manipulating-innerhtml-removes-the-event-handler-of-a-child-element). – Sebastian Simon Aug 06 '18 at 12:55
  • you may add something like this and inside JavaScript function `document.getElementById("Headline").classList.add("active");` – Nisarg Aug 06 '18 at 13:00

2 Answers2

0

There are two ways to fix it.

  1. Use classList property: The classList property is not supported in IE9 and earlier.

this.classList.add("active");

  1. Use setAttribute method

this.setAttribute('class','active');

OR

this.setAttribute('class',this.getAttribute('class')+' active');

Onkar Janwa
  • 3,892
  • 3
  • 31
  • 47
0

Considering you want to add class to the element with id "myDIV".

 var element = document.getElementById("myDIV");
 element.classList.add("mystyle");
Akarsh ts
  • 39
  • 4