Classname Only Changing Every Other Class

Get All Elements By ClassName and Change ClassName

The problem is that the NodeList returned to you is "live" - it changes as you alter the class name. That is, when you change the class on the first element, the list is immediately one element shorter than it was.

Try this:

  while (elementArray.length) {
elementArray[0].className = "exampleClassComplete";
}

(There's no need to use setAttribute() to set the "class" value - just update the "className" property. Using setAttribute() in old versions of IE wouldn't work anyway.)

Alternatively, convert your NodeList to a plain array, and then use your indexed iteration:

  elementArray = [].slice.call(elementArray, 0);
for (var i = 0; i < elementArray.length; ++i)
elementArray[i].className = "whatever";

As pointed out in a comment, this has the advantage of not relying on the semantics of NodeList objects. (Note also, thanks again to a comment, that if you need this to work in older versions of Internet Explorer, you'd have to write an explicit loop to copy element references from the NodeList to an array.)

Change class name depending on existing class name

Below code will work when you click on the same div again.

Note: As pere requirement when a div already has w-60 and you click on other div that have w-20 it will not reset the class.

function changeClass(div_number) {
var fp = document.getElementById("first-project");
var sp = document.getElementById("second-project");
var tp = document.getElementById("third-project");

if (div_number == 1) {
if (fp.classList.contains("w-60")) {
resetClassname(fp, sp, tp);
}

else {
fp.className = "w-60";
sp.className = "w-20";
tp.className = "w-20";
}
}

if (div_number == 2) {
if (sp.classList.contains("w-60")) {
resetClassname(fp, sp, tp);
}
else {
fp.className = "w-20";
sp.className = "w-60";
tp.className = "w-20";

}
}
if (div_number == 3) {
if (tp.classList.contains("w-60")) {
resetClassname(fp, sp, tp);

}
else {
fp.className = "w-20";
sp.className = "w-20";
tp.className = "w-60";
}
}
}
function resetClassname(fp, sp, tp) {
fp.className = "w-33";
sp.className = "w-33";
tp.className = "w-33";
}

getElementsByClassName strange behavior, skipping certain elements

You can use querySelectorAll and classList instead of the live nodelist you get with getElementsByClassName

function swapClasses() {
// Get all elements of class B
[...document.querySelectorAll(".classb")].forEach(div => {
div.classList.add("classa");
div.classList.remove("classb");
// Swap the text as well
div.textContent = "Class A";
})
}
.classa {
background-color: red;
}

.classb {
background-color: green;
}
<div class="classa">Class A</div>
<div class="classb">Class B</div>
<div class="classb">Class B</div>
<div class="classb">Class B</div>
<div class="classb">Class B</div>
<button onclick="swapClasses();">Swap class B to class A</button>

nth-child, change style of every other div with class name

Here is the solution, I put the nth-child in the wrong place.

.stagger_reviews > article:nth-child(2n+2) div[class=inner]

How can I replace one class with another on all elements, using just the DOM?

Explanation

document.getElementsByClassName returns an HTMLCollection, not just an array of elements. That means that the collection is live, so in this specific situation, it retains the requirement that it will always hold all elements with the class "current".

Coincidentally, you are removing the very class that the collection depends on, therefore updating the collection. It would be totally different if you were setting the value property (for example) in the loop - the collection wouldn't be affected, because the class "current" wasn't removed. It would also be totally different if you were adding a class, such as el.className += " none";, but that isn't the case.

A great description from the MDN docs:

HTMLCollections in the HTML DOM are live; they are automatically updated when the underlying document is changed.

Approach 1

An easy way to overcome all this pandemonium is by looping backwards.

var els = document.getElementsByClassName('current'),
i = els.length;

while (i--) {
els[i].className = 'none';
}

DEMO: http://jsfiddle.net/fAJgT/

(the code in the demo has a setTimeout, simply so you can see the original border color at first, then after 1.5 seconds, see it change)

This works because it modifies the last item in the collection - when it is modified (and automatically removed), move onto the item before it. So it doesn't suffer any consequences of the automatic removal.

An alternate setup, doing the same thing, is:

for (i = els.length; i >= 0; i--) {

Approach 2

Another answer made me realize you could just continually operate on the first item found. When you remove the specific class, the element is removed from the collection, so you're guaranteed that the first item is always a fresh item in the collection. Therefore, checking the length property should be a safe condition to check. Here's an example:

var els = document.getElementsByClassName('current');
while (els.length) {
els[0].className = 'none';
}

DEMO: http://jsfiddle.net/EJLXe/

This is basically saying "while there's still items in the collection, modify the first one (which will be removed after modified)". I really wouldn't recommend ever using that method though, because it only works specifically because you end up modifying the collection. This would infinitely loop if you were not removing the specific class, or with a normal array or a non-live collection (without spliceing).

Approach 3

Another option is to slice (shallow copy) the collection into an array and loop through that normally. But I don't see any reason/improvement to do that. Here's an example anyways:

var els = document.getElementsByClassName('current'),
sliced = Array.prototype.slice.call(els), i;

for (i = 0; i < sliced.length; i++) {
sliced[i].className = 'none';
}

DEMO: http://jsfiddle.net/LHe95/2/

Approach 4

Finally, you could use document.querySelector - it returns a non-live NodeList (therefore you can loop like normal), and even has better support in browsers than document.getElementsByClassName does. Here's an example:

var els = document.querySelectorAll('.current'),
i;

for (i = 0; i < els.length; i++) {
els[i].className = 'none';
}

DEMO: http://jsfiddle.net/xq8Xr/


References:

  • document.getElementsByClassName: https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByClassName
  • HTMLCollection: https://developer.mozilla.org/en-US/docs/DOM/HTMLCollection
  • slice: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice
  • querySelectorAll: https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll

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 behaviour. 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 change a single element of one class without using a different class name

Here are two ways. First is add another class and change that one property alone, the second class property will replace the previous class property if its present in both.

Second approach will be to just write it as an inline style. No need for the extra class!