n00bly
n00bly

Reputation: 395

Javascript - Add class to a class (not ID)

In a HTML file i load a javascript file (in the header) which contains some code. In that code it checks if a cookie exists. If the cookie doesn't exists it should add a class to a div which should be matched with a class.

Example:

The class where it should add the class:

<header class="firstClass">

The javascript:

var classcode = document.getElementsByClassName("firstClass");

if (myCookie == null) {
    add class "secondClass" to "firstClass";
}

I've tried several things but I can't get it to work...

I should mention, the javascript file is loaded before the div where the class should be added.

Upvotes: 0

Views: 161

Answers (5)

n00bly
n00bly

Reputation: 395

I think all solutions will work. The problem was that I had to load the javascript file after the div which should get the class added. Thanks al for the help! :)

Upvotes: 0

You could use querySelectorAll, in order to find all the elements with the class firstClass. This will result in an array, then you just have to loop through it.

var classcode = document.querySelectorAll(".firstClass");

classcode.forEach(function(element) {
    element.classList.add("mystyle")
  console.log(element);
});

Upvotes: 2

brk
brk

Reputation: 50326

document.getElementsByClassName returns a collection. Use spread operator to convert it into array and use array methods(forEach) in this case. Then check if the array length is greater than 0, if greater than 0 then add another class using classList.add

var classcode = [...document.getElementsByClassName("firstClass")];
if (classcode.length > 0) {
  classcode.forEach(function(item) {
    item.classList.add('anotherClass')
  })
}
.anotherClass {
  color: green;
}
<header class="firstClass">Header Here</header>
<div class="someOtherClass"> Some Text</div>
<div class="firstClass">Another Text</div>

Upvotes: 0

Mr. Roshan
Mr. Roshan

Reputation: 1805

Try this:-

var classcode = document.getElementsByClassName("firstClass");
if (myCookie == null) {
    classcode .classList.add("secondClass");
}

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You need to use classList.add() to each of the elements that has class firstClass. Although you might have single element, but it is better to use a loop for selecting each element so that in future when you add element in HTML with this same class then you do not need to change the JS code.

var classcode = document.getElementsByClassName("firstClass");

for(var i=0; i<classcode.length; i++){
   classcode[i].classList.add('secondClass');
}
.secondClass{
  color: green;
}
<div class="firstClass">1</div>
<div class="firstClass">2</div>
<div class="firstClass">3</div>

Upvotes: 1

Related Questions