Nic Stelter
Nic Stelter

Reputation: 661

Changing fontSize for a class using Javascript

<div id="release-0">
  <p class="release-4"> Here is some text, add a class "done" to the parent div</p>
</div>

<div id="release-1">
  <p>remove the #release-1 div</p>
</div>

<h1>Change this text to finish release 2</h1>

<div id="release-3">
  <p class="release-4"> add CSS to this div</p>
</div>

How do I select all occurrences of class .release-4 and change the text-size to 2em using Javascript?

I've tried this:

document.getElementsByClassName("release-4").style.fontSize = "2em";

but that doesn't work.

This does work:

document.getElementsByClassName("release-4")[0].style.fontSize = "2em";

but it only selects the first occurrence of .release-4.

Upvotes: 8

Views: 15026

Answers (5)

DDA
DDA

Reputation: 161

css

    .newClass {
  fontSize: 2em;
}

javascript

var el=document.getElementsByClassName('release-4');
for(var i=0, var tot=el.length; i < tot; i++){
    el[i].className = " release-4  newClass ";
}

to remove class newClass: same for loop and

el[i].className = " release-4 ";

to remove class release-4: same for loop and

el[i].className = " newClass ";

to remove class newClass you can also use

el[i].className = el[i].className.replace(" newClass ","");

Upvotes: 0

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

You can use querySelectorAll to select which class, then loop throught the returned collection, here is an example:

var el = document.querySelectorAll(".release-4");
for ( var i = 0; i < el.length; i ++ ) {
    el[i].style.fontSize = "2em";
}

http://jsfiddle.net/9px6LyLp/

Upvotes: 1

danielm
danielm

Reputation: 66

You'll need to loop over the NodeList that is returned by .getElementsByClassName() and apply your change to each element.

var elements = document.getElementsByClassName('release-4');

for (var i = 0; i < elements.length; i++) {
  var element = elements[i];
  element.style.fontSize = "2em";
}

Upvotes: 4

Seth McClaine
Seth McClaine

Reputation: 10030

I would recommend adding a new class to each element instead of editing each style individually

.newClass {
  font-size: 2em;
}

I know your question is asking for JavaScript, but JQuery has a much quicker resolution.

//Add a class
$(".release-4").addClass('newClass');
//If you want to remove the existing class after
$(".release-4").addClass('release-4');

If you still want to set the styles manually you can do:

$(".release-4").css('font-size','2em');

JQuery loops through all instances of the class for you

Upvotes: -1

Caminante
Caminante

Reputation: 46

getElementsByClassName() method returns a collection of elements. You should loop through them and set the necessary font value for each element individually.

Upvotes: 3

Related Questions