Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change paragraph font size back and fourth on all paragraphs

how can i make this code work on all paragraphs on a website, this is just an example code. i want it the change all paragraphs font sizes up and down with the click of the button. right now its only changing the first paragraph

<button type="button" onclick="change_font_size();">Change font size</button>
<p id="p"> this is some text </p>
<p id="p"> this is also some text </p>

<script>
var font_is_large = false ;
function change_font_size( )
{
  paragraph = document.getElementById( 'p' );
  if (!font_is_large) {
    paragraph.style.fontSize = "150%" ;
    font_is_large = true ;
  }
  else {
    paragraph.style.fontSize = "100%" ;
    font_is_large = false ;
  }
}
</script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Change ids to classes. Use querySelectorAll instead of getElementById and use forEach to go through every element. You don’t need variable font_is_large and you can replace it with p.style.fontSize !== "150%".

function change_font_size( )
{
  paragraphs = document.querySelectorAll('.p');
  paragraphs.forEach((p) => {
     if (p.style.fontSize !== "150%") {
       p.style.fontSize = "150%" ;
     }
     else {
        p.style.fontSize = "100%" ;
      }
  })
}
<button type="button" onclick="change_font_size();">Change font size</button>
<p class="p"> this is some text </p>
<p class="p"> this is also some text </p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading