Although the usual way to do it is a two-step technique, try this:
const el = Object.assign(document.createElement('div'), { className: 'foo' });
console.log(el);
console.log(el.className);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from Majed Badawi on Stack OverflowAlthough the usual way to do it is a two-step technique, try this:
const el = Object.assign(document.createElement('div'), { className: 'foo' });
console.log(el);
console.log(el.className);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You're stuck with either using an HTML string and innerHTML or trying jQuery which allows the chaining of commands, but for something so small it doesn't make sense to bring jQuery into the mix, what's the reason you needed a one-liner?
For a rough working example in vanilla js
var myHTML = "<div class='hello'></div>";
document.body.innerHTML += myHTML
How to append multiple classes to an element? JavaScript DOM
How can I add a class to a DOM element in JavaScript? - Stack Overflow
Setting class to a DOM element
Problem with document.getElementsByClassName().innerHTML
I'm sooo sorry if this is a massively newbie question, but I'm not quite sure how to search for this. Everything I find shows me how to append 1 class to an element. Essentially what I'm trying to do is convert this HTML to Javascript DOM:
<section class="location">
<h2>
<div class="city">Pompano Beach, US</div>
</h2>
<div class="date">Fri, August 4, 2020</div>
</section>This is what I have so far:
var loc = document.createElement("SECTION");
loc.setAttribute("class", "location");
workspace.appendChild(loc);
var city = document.createElement("DIV");
city.setAttribute("class", "city");
workspace.appendChild(city);
let h3 = document.createElement('h3');
text = document.createTextNode("Pompano Beach, US");
h3.appendChild(text);
workspace.getElementsByClassName("location").appendChild(h3);Anything would be helpful!! Thank you!
This answer was written/accepted a long time ago. Since then better, more comprehensive answers with examples have been submitted. You can find them by scrolling down. Below is the original accepted answer preserved for posterity.
new_row.className = "aClassName";
Here's more information on MDN: className
Use the .classList.add() method:
const element = document.querySelector('div.foo');
element.classList.add('bar');
console.log(element.className);
<div class="foo"></div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
This method is better than overwriting the className property, because it doesn't remove other classes and doesn't add the class if the element already has it.
You can also toggle or remove classes using element.classList (see the MDN documentation).