How to add CSS class - in JavaScript?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to add CSS class - in JavaScript?



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?


this.classlist.add("active");




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>





It’s classList, not classlist. Also, when you overwrite innerHTML all your event listeners get lost.
– Xufox
Aug 6 at 12:55



classList


classlist


innerHTML





you may add something like this and inside JavaScript function document.getElementById("Headline").classList.add("active");
– Nisarg
Aug 6 at 13:00


document.getElementById("Headline").classList.add("active");




2 Answers
2



There are two ways to fix it.



this.classList.add("active");



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



OR



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





Thank you very much! That was the clue - perfect!
– MrSeelvuple
Aug 7 at 14:24



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


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered