How to Redefine CSS Classes with JavaScript

How to redefine CSS classes with Javascript

I don't know about manipulating the class directly, but you can effectively do the same thing. Here's an example in jQuery.

$('.colourful').css('background-color', 'purple').css('color','red');

In plain javascript, you would have to do more work.

Change CSS of class in Javascript?

You can do that — actually change style rules related to a class — using the styleSheets array (MDN link), but frankly you're probably better off (as changelog said) having a separate style that defines the display: none and then removing that style from elements when you want them no longer hidden.

Modify CSS classes using Javascript

The reason only one or the other works is because in your second line of code, you destroy the whole style attribute, and recreate it. Note that setAttribute() overwrites the whole attribute.

A better solution would be to use the element.style property, not the attribute;

var bg = document.getElementById("myBg");
bg.style.width = imgWidth + "px";
bg.style.height = imgHeight + "px";

You can grab all elements with class container and apply it to each of them like this:

var elements = document.querySelectorAll('.container');
for(var i=0; i<elements.length; i++){
elements[i].style.width = imgWidth + "px";
elements[i].style.height = imgHeight + "px";
}

Note querySelectorAll isn't supported by IE7 or lower, if you need those then there are shims for getElementsByClassName() here on SO.

Change the style of an entire CSS class using javascript

The key is to define extra rules for additional classes and add these classes to the elements rather than to rewrite the rules for a given style rule.

JS

function changeCSS() {
var selects = document.getElementsByTagName("select");
for(var i =0, il = selects.length;i<il;i++){
selects[i].className += " hidden";
}
}

CSS

.fool select.hidden, select.hidden {
display: none;
}

Or for a really efficient method (but which might need a few more specific style rules too)

JS

function changeCSS() {
document.getElementsByTagName("body")[0].className += " hideAllSelects"
}

CSS

body.hideAllSelects select {
display: none;
}

Is it possible to change entire css class / js and anything associate with that?

Others have mentioned Jquery.

You could also do it dynamically with Less Mixins: https://www.gaslampmedia.com/mapping-css-styles-less/.

Or you could do it non-dynamically (I would recommend this). You could use an IDE (Integrated Development Environment) or an advanced text editor to search and replace all instances of a text string in the entire project at once. In your case, you could replace all instances of mcdonald with the name of your company or project. Advanced Text Editors like Sublime Text or Notepad++ could let you do this, but you would generally need to open all of the files at once. IDEs like Visual Studio or Dreamweaver would also let you do this, with the benefit of not having to open all of the files (you just add the files to your project).

How to change a css class style through Javascript?

Suppose you have:

<div id="mydiv" class="oldclass">text</div>

and the following styles:

.oldclass { color: blue }
.newclass { background-color: yellow }

You can change the class on mydiv in javascript like this:

document.getElementById('mydiv').className = 'newclass';

After the DOM manipulation you will be left with:

<div id="mydiv" class="newclass">text</div>

If you want to add a new css class without removing the old one, you can append to it:

document.getElementById('mydiv').className += ' newClass';

This will result in:

<div id="mydiv" class="oldclass newclass">text</div>

How can I change an element's class with JavaScript?

Modern HTML5 Techniques for changing classes

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

if ( document.getElementById("MyElement").classList.contains('MyClass') )

document.getElementById("MyElement").classList.toggle('MyClass');

Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.

Simple cross-browser solution

The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

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

(You can use a space-delimited list to apply multiple classes.)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

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

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */

An explanation of this regex is as follows:

(?:^|\s) # Match the start of the string or any single whitespace character

MyClass # The literal text for the classname to remove

(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

To check if a class is already applied to an element:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )


### Assigning these actions to onClick events:

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onClick="this.className+=' MyClass'") this is not recommended behavior. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onClick attribute, for example:

<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onClick="changeClass()">My Button</button>

(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)

The second step is to move the onClick event out of the HTML and into JavaScript, for example using addEventListener

<script type="text/javascript">
function changeClass(){
// Code examples from above
}

window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>

(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)



JavaScript Frameworks and Libraries

The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.

Whilst some people consider it overkill to add a ~50  KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.

(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)

The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).

(Note that $ here is the jQuery object.)

Changing Classes with jQuery:

$('#MyElement').addClass('MyClass');

$('#MyElement').removeClass('MyClass');

if ( $('#MyElement').hasClass('MyClass') )

In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:

$('#MyElement').toggleClass('MyClass');


### Assigning a function to a click event with jQuery:
$('#MyElement').click(changeClass);

or, without needing an id:

$(':button:contains(My Button)').click(changeClass);


CSS styles doesn't change after adding class with JavaScript

You set a background-color via an id, then you set another via a class, the first one will always be applied, because it has a higher specificity. Change #sort-select selector by a class in your CSS, or use inline styling like this:

var selected = false;
select.onclick = (e) => {
selected = !selected;
if (selected)
slect.style.backgroundColor ="gray"
else
slect.style.backgroundColor ="lightgray"
};

Also you could use !important keyword, like so :

.sort-select-active {
background-color: grey!important;
}


Related Topics



Leave a reply



Submit