0

How would I set mulitple CSS classes for an HTML element, with at least one normal class and one or more Javascript variables as classes?

Here's how I tried to do it, putting it in like a normal script:

<div class="style-a <script type="text/javascript">style-b</script>">

Then I saw that someone recommend this:

<div onload="this.class=style-a;">

But I'm pretty sure that would only work for one class.

Thoughts? Thanks in advance.

4
  • 1
    I'm pretty sure this.class wouldn't work for any classes, as it's this.className. In newer browser you can use this.classList.add('style-a'). Commented Apr 24, 2015 at 14:27
  • Have you tried separating the class names with a space to get multiple class names? Something like this.class='style-a class2'? Commented Apr 24, 2015 at 14:37
  • @Patrick548 No, I hadn't. I'll try that. Commented Apr 24, 2015 at 14:44
  • Neither of the above solutions worked for me. Thanks anyway. Commented Apr 24, 2015 at 15:09

2 Answers 2

2

Use setAttribute

var element = document.getElementById('myDiv');
element.setAttribute('class','class1 class2');

See it in action

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot insert script elements in html attributes to insert data computed by dynamically evaluated code.

Instead you might apply the following template:

<div id="#dyn-styles-1" class="style-a">
    <!-- div contents -->
</div>

<!-- ... -->

<script>
    //
    // Beware:
    //  - Execute _after_ the complete DOM has been built ( use handlers for `load` or `DOMContentLoaded` events)
    //  - Proof of concept only: coding style not recommended for production code
    //
    var js_var_containing_class = "style-b";

    //...

    document.getElementById("dyn-styles-1").className = document.getElementById("dyn-styles-1").className + " " + js_var_containing_class;

</script>

You need not rely on IDs but may refer to existing css classes instead:

var el = document.getElementsByClassName("style-a");

for (var i=0; i< el.length; i++) {
    el[i].className = el[i].className + " " + js_var_containing_class;
}

1 Comment

I tried this, but for some reason the class stays "style-a". Not sure why. Thanks though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.