Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing fontSize for a class using Javascript

Tags:

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.

like image 862
Nic Stelter Avatar asked May 13 '15 13:05

Nic Stelter


People also ask

How can you change the font size using JavaScript?

To change the font size of a div using JavaScript, get reference to the div element, and assign required font size value to the element. style. fontSize property.

How do you change text size code?

In HTML, you can change the size of text with the <font> tag using the size attribute. The size attribute specifies how large a font will be displayed in either relative or absolute terms. Close the <font> tag with </font> to return to a normal text size.


1 Answers

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

like image 141
Caminante Avatar answered Oct 05 '22 13:10

Caminante