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

How to change font size of all paragraphs in div with Javascript?

I’m trying to change the font size and line height of all paragraphs in my div depending on the size of the screen–for mobile responsiveness. As you can see in the example, when I attempt to change the paragraph sizes with JS, it only alters the first element. When I do it in CSS it works, just not JS.

const textContP = document.querySelector('.textcont p');
textContP.setAttribute("style", "line-height: 5vw");
textContP.style.fontSize = "3vw";
.textcont p {
      font-size: 4vw;
      line-height: 5vw
  }
<div class="textcont">
  <p>test</p>
  <p>test2</p>
</div>

>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

The problem is the document.querySelector(). It selects just the first element found. You need to use document.querySelectorAll() to get all <p> tags.

document.querySelectorAll('.textcont p').forEach(p => {
  p.style.lineHeight = "5vw";
  p.style.fontSize = "3vw";
})
.textcont p {
      font-size: 4vw;
      line-height: 5vw
  }
<div class="textcont">
  <p>test</p>
  <p>test2</p>
</div>
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