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 >
<p>test</p>
<p>test2</p>
</div>
CodePudding user response:
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 >
<p>test</p>
<p>test2</p>
</div>
CodePudding user response:
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 use forEach
to iterate over the returned node list updating the style for each paragraph.
setTimeout(() => {
const paras = document.querySelectorAll('.textcont p');
paras.forEach(p => {
p.style.lineHeight = '4vw';
p.style.fontSize = '3vw';
});
}, 2000);
.textcont p {
line-height: 5vw;
font-size: 4vw;
}
<div >
<p>test</p>
<p>test2</p>
</div>
Solution two
Adjust the underlying stylesheet using CSS variables instead.
setTimeout(() => {
const { style } = document.documentElement;
style.setProperty('--lineHeight', '4vw');
style.setProperty('--fontSize', '3vw');
}, 2000);
:root {
--lineHeight: 5vw;
--fontSize: 4vw;
}
.textcont p {
line-height: var(--lineHeight);
font-size: var(--fontSize);
}
<div >
<p>test</p>
<p>test2</p>
</div>
CodePudding user response:
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 using for loop
or for 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 selectors
const textContP = document.querySelectorAll('.textcont p');
textContP.forEach(item => {
item.style.lineHeight = "5vw";
item.style.fontSize = "3vw";
});
learn more about loops here