thebeast22
thebeast22

Reputation: 103

How to change font-size of multiple elements using jQuery

I need to increment the font-sizes of my elements by 1. I already did this, but the long way.

HTML

<div id="container">
<h3 class="heading">
  24px font
</p>
<p class="content">
  12px font
</p>
<span class="footNote">
  10px font
</span>
<button id="upSize">Larger</button>

CSS

.heading {
  font-size: 24px;
}

.content {
  font-size: 12px;
}

.footNote {
  font-size: 10px;
}

jQuery

$(function() {
 $("#upSize").click(function() {
    var headingSize = parseInt($(".heading").css("font-size"));
    var contentSize = parseInt($(".content").css("font-size"));
    var footNoteSize = parseInt($(".footNote").css("font-size"));
    headingSize = headingSize + 1 + "px";
    contentSize = contentSize + 1 + "px";
    footNoteSize = footNoteSize + 1 + "px";
    $(".heading").css({'font-size':headingSize});
    $(".content").css({'font-size':contentSize});
    $(".footNote").css({'font-size':footNoteSize});
  });
});

My problem is, how can I target all elements at once? Without creating many lines?

Upvotes: 3

Views: 3895

Answers (2)

Hebe
Hebe

Reputation: 810

I needed to increase font-size of all elements. But caveat lies in font-size inheritance, so I needed to get all leaf nodes as well with another caveat upon tags like br inside text

function addFontSize(fontAddition){
    $("*").filter(function() {
          return $(this).children('body,div,span').length == 0;
    }).each(function() {
        var size = parseInt($(this).css("font-size"));
        size = size + fontAddition + "px";
        $(this).css({
            'font-size': size
        });
    });
}
addFontSize(1);

Upvotes: 0

Rino Raj
Rino Raj

Reputation: 6264

You can loop through every child of div and change corresponding element using$(this)

Working Demo

$(function() {
  $("#upSize").click(function() {
    $("div").children().each(function() {
      var size = parseInt($(this).css("font-size"));
      size = size + 1 + "px";
      $(this).css({
        'font-size': size
      });
    });
  });
});
.heading {
  font-size: 24px;
}
.content {
  font-size: 12px;
}
.footNote {
  font-size: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p class="heading">
    24px font
  </p>

  <p class="content">
    12px font
  </p>

  <span class="footNote">
    10px font
  </span>

  <button id="upSize">Larger</button>

For Reference

.children()

$(this)

Upvotes: 4

Related Questions