How to Append a CSS Class to an Element by JavaScript

how to append a css class to an element by javascript?

var element = document.getElementById(element_id);
element.className += " " + newClassName;

Voilà. This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).

Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.

In prototype, for instance:

// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);

See how much nicer that is?!

How to add a class to a given element?

If you're only targeting modern browsers:

Use element.classList.add to add a class:

element.classList.add("my-class");

And element.classList.remove to remove a class:

element.classList.remove("my-class");

If you need to support Internet Explorer 9 or lower:

Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>

Then

var d = document.getElementById("div1");
d.className += " otherclass";

Note the space before otherclass. It's important to include the space otherwise it compromises existing classes that come before it in the class list.

See also element.className on MDN.

How can I add a class to a DOM element in JavaScript?

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

How to add element to existing css class

The problem here is that you cannot add stuff to the parsed CSS. You can only add inline styles to a particular element. Say, you had a <div class="usrgrid">. The only modification you do it this: <div class="usrgrid" style="color: red">. Examples presented here using .css do exactly this.

Other options are:

  1. Add CSS code dynamically
  2. Link CSS file dynamically

Update

So, I realised now from where the problem comes. You have an element, you want to modify it somehow. For example, it was invisible and then became visible or it had the white background and then became yellow, whatever. The key point here is that you have your initial state and "modifier" for it. If you take the modifier away, you get back to where things began. From CSS point of view it means:

.my-elem {}

.my-elem--big {}

.my-elem--yellow {}

.my-elem--visible {}

Now, in your JS you only need to add a proper set of modifiers (classes) to you element.

<div class="my-elem"></div>

<div class="my-elem my-elem--visible"></div>

There is a naming convention for CSS called BEM. It solved exactly this problem. In a nutshell, you split your UI into blocks, elements and modifiers.

By following this approach you separate concerns (the logic of when the element should become visible, JS, and what does it mean that it is visible, CSS) and make your code more pleasant to work with (ubiquitous structure and predictability).

I personally, always try to avoid any CSS in my JS. Even if it just display: block. Because these two are meant for different things.

JavaScript CSS how to add and remove multiple CSS classes to an element

Try doing this...

document.getElementById("MyElement").className += " MyClass";

Got this here...

Safe AND quickest way to add a css class to the body of the DOM

document.body.className += ' home';

Performance comparision: className vs classList vs addClass :

Update(based on PSL's comment)

or for newer ones document.body.classList.add("home");

Make sure you do this under the <body>, it won't work if applied from a <head> script

How to dynamically change CSS class of an HTML tag?

You can add a CSS class based on id dynamically using classList API as follows:

document.getElementById('idOfElement').classList.add('newClassName');

Or the old way:

document.getElementById('idOfElement').className = 'newClassName';
// += to keep existing classes

Alternatively you can use other DOM query methods shown below to find elements. The last three return a collection so you'll have to iterate over it and apply the class to each element in the collection (similar to the example given below each).

  • querySelector

  • querySelectorAll

    elements.forEach(element => element.classList.add('newClassName'));
  • getElementsByClassName

    Array.from(elements).forEach(element => element.classList.add('newName'));
  • getElementsByTagName

    Array.from(elements).forEach(element => element.classList.add('newName'));

In your case

var element = document.getElementById('div1');
if(boolVal)
element.className= 'blueClass'; // += ' blueClass'; to keep existing classes
else
element.className= 'redClass';

Use javascript to add a CSS class to all elements with another class name

Since it appears you are using jQuery:

Live Demo

$(document).ready(function () {
$('.buttonSubmit').addClass('btn');
});

Without jQuery:

Live Demo

window.onload = function() {
var buttons = document.getElementsByClassName("buttonSubmit"),
len = buttons !== null ? buttons.length : 0,
i = 0;
for(i; i < len; i++) {
buttons[i].className += " btn";
}
}

Javascript: Append Element to a Class Only on Specific .html File

you can use ID attribute of the element. something like:

<div id="posts_of_about" class="posts">

and your js can be something like this:

newDiv = document.createElement('div');
postContent = document.querySelector("#posts_of_about");
postContent.append(newDiv);

its only one of a lot of solutions.



Related Topics



Leave a reply



Submit