Search code examples
javascriptobjectproperties

Adding values from a JavaScript object as classes on an element


In JavaScript, how would I take the values of an object and add each one as a separate class on an element in the DOM?

For instance, let's say I have this object:

const METADATA = {
    foo: 'test1',
    bar: 'test2'
};

I want to add the values present within this object as two separate classes on the <html> tag.

In order to achieve this, I tried to specify the properties of the METADATA object within the jQuery .addClass method:

$('html').addClass( METADATA["foo","bar"] );

But this only added the last value of the object as a class on the <html> tag, which has left me fairly confused.

Any thoughts?


Solution

  • METADATA["foo","bar"] only gets the value of the bar property, because you're using the comma operator, which is a bit odd: It evaluates its first operand ("foo"), throws that value away, then evaluates its second operand ("bar") and takes that as its result. So it's the same as METADATA["bar"] or METADATA.bar (because evaluating "foo" has no side-effects).

    Instead, you need to get each value separately:

    $('html').addClass([METADATA.foo, METADATA.bar]);
    

    That works because addClass allows you to provide an array of class names to add. (Alternatively, just call addClass twice.)

    Or without jQuery:

    document.documentElement.classList.add(METADATA.foo, METADATA.bar);
    

    The add method of DOMTokenList allows you to specify multiple class names to add as discrete arguments.