user9581798
user9581798

Reputation:

How to change fontsize using a for loop

I have a Uni assignment that says I should change the font size of the anchor tags using a for loop.

var actiVe = document.getElementsByTagName('a');
for (var i = 0; i < actiVe.length; i++) {
  actiVe[i].style.fontSize = (parseInt(actiVe[i].style.fontSize) * 2 + 'px')
}
<nav>
  <ul>
    <!-- 
							1. Weise mittels einer Schleife allen Listenelementen eine andere Schriftgröße zu. Recherchiere gegebenenfalls nach "JavaScript Style Object Properties".
						-->
    <li class="active"><a href="index.html">Home</a></li>
    <li><a href="">About</a></li>
    <li><a href="">Blog</a></li>
    <li><a href="">Contact</a></li>
  </ul>
</nav>

Upvotes: 0

Views: 402

Answers (1)

baao
baao

Reputation: 73301

You should get the computed font size value instead, element.style.fontSize will return an empty string in some cases, for example for externally set font sizes (e.g. via css)

var actiVe = document.getElementsByTagName('a');
for (var i = 0; i < actiVe.length; i++) {
  let fontSize = parseFloat(window.getComputedStyle(actiVe[i], null).getPropertyValue('font-size'));
  actiVe[i].style.fontSize = fontSize * 2 + 'px'
}
<ul>
  <!-- 
                        1. Weise mittels einer Schleife allen Listenelementen eine andere Schriftgröße zu. Recherchiere gegebenenfalls nach "JavaScript Style Object Properties".
                    -->
  <li class="active"><a href="index.html">Home</a></li>
  <li><a href="">About</a></li>
  <li><a href="">Blog</a></li>
  <li><a href="">Contact</a></li>
</ul>

Upvotes: 2

Related Questions