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

Forums jQueryHow to change font size of all paragraphs in div with Javascript?
Staff asked 3 months ago

For mobile responsiveness, I’m attempting to adjust the font size and line height of all paragraphs in my div based on the size of the screen. As you can see in the example, changing the paragraph widths with JS only affects the first element. It works fine in CSS, but not in 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>

 

Answers (1)

Add Answer
Prince Dhameliya Marked As Accepted
Staff answered 3 months ago

The document.querySelector is the issue (). It selects just the first element found. To obtain all p> tags, use document.querySelectorAll().

document.querySelectorAll('.textcont p').forEach(p => {
  p.style.lineHeight = "5vw";
  p.style.fontSize = "3vw";
})
.textcont p {
      font-size: 4vw;
      line-height: 5vw
  }
.textcont p {
      font-size: 4vw;
      line-height: 5vw
  }

 

Subscribe

Select Categories