Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading