Home > Blockchain >  change paragraph font size back and fourth on all paragraphs
change paragraph font size back and fourth on all paragraphs

Time:10-13

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>

CodePudding user response:

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 > this is some text </p>
<p > this is also some text </p>

  • Related