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>
3
Answers
The problem is the
document.querySelector()
. It selects just the first element found. You need to usedocument.querySelectorAll()
to get all<p>
tags.querySelector
selects only the first element.so use
querySelectorAll
this will put all selected elements in an array, then you can loop through the array usingfor loop
orfor each
to change all the elements.NOTE: make sure you give all elements the same class for that. and make sure to add the dot
.
when you add classes in selectorslearn more about loops here
Note: I’ve used a time out in both these examples to show them working.
Solution one
Use
querySelectorAll
to grab all the paragraphs and useforEach
to iterate over the returned node list updating the style for each paragraph.Solution two
Adjust the underlying stylesheet using CSS variables instead.