+ 1

How to add classes to elements in JS

How can I add a class to an element only using JavaScript? Edit: Apparently I was unclear, I meant HTML element.

16th Apr 2018, 5:51 PM
fallOut015
fallOut015 - avatar
5 Respostas
+ 12
using pure JavaScript given the element: <div id="my-div"></div> var myDiv = document.getElementById("my-div"); myDiv.classList.add("my-div-new-class"); demo https://code.sololearn.com/WT2gG9uO5VLG/?ref=app
16th Apr 2018, 6:18 PM
Burey
Burey - avatar
+ 5
t's important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the "class"-ical languages. https://www.phpied.com/3-ways-to-define-a-javascript-class/
16th Apr 2018, 5:59 PM
Scooby
Scooby - avatar
+ 5
https://www.w3schools.com/tags/att_global_class.asp The benefit of this is that you can have the same HTML element, but present it differently depending on its class or ID. In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”).
16th Apr 2018, 6:03 PM
Scooby
Scooby - avatar
+ 4
create your element without a class in html first <p>hello</p> #js p=document.querySelector("p"); p.setAttribute("class","myclass"); As easy as pie
16th Apr 2018, 6:10 PM
᠌᠌Code X
᠌᠌Code X - avatar
0
S.D sorry if I was unclear, I meant add a class to an HTML element
16th Apr 2018, 6:00 PM
fallOut015
fallOut015 - avatar