如何在JavaScript中添加CSS类?

时间:2018-08-06 12:54:04

标签: javascript css class styles

最近我遇到了这个问题:

如果在JS:22行中我添加了this.classlist.add("active");,则它应根据CSS类更改颜色,但不起作用。任何想法?

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>

2 个答案:

答案 0 :(得分:0)

有两种解决方法。

  1. 使用classList属性:IE9和更早版本不支持classList属性。
  

this.classList.add(“ active”);

  1. 使用setAttribute方法
  

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

OR

  

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

答案 1 :(得分:0)

考虑要向id为“ myDIV”的元素添加类。

 var element = document.getElementById("myDIV");
 element.classList.add("mystyle");