Home > database >  How to change font size by javascript from css
How to change font size by javascript from css

Time:02-22

I have some css.

.A B{
  font-size:34%
}

How can I change font-size from 34% to 30%? by javascript. I tried some script like this.

document.querySelectorAll('.card-full, .card-text')[0].style.fontSize='30%';

But, font size is changed weird.
And Chrome DevTools show Elements information like this.

.A B{
  font-size:34%
}
style attribute {
  ~~font-size:30%;~~
}

Oh... stackoverflow can't support strikethrough.

How can I change font size from css by javascript?

CodePudding user response:

It is very unclear what you want. Your spaces and commas and missing dots make it tricky to guess

Here is an example of what I think you meant - the 90% is for illustration

document.querySelector('.card-full .card-text').style.fontSize='90%';
.A .B{
  font-size:34%
}
<div >First card<p >Some text</p></div>
<div >Second card<p >Some text</p></div>

CodePudding user response:

It is strikethrough most likely because there're other css that has higher specificity.

The way you change the font-size using JS is correct. It would be helpful if you provide more details.

Edit: the arg inside querySelectorAll is probably not what u want as mentioned by @mplungjan.

document.querySelectorAll('.card-full, .card-text')[0].style.fontSize='30%';

The above will change the card-full element's font-size instead of the first card-text

CodePudding user response:

document.getElementsByClassName('B')[0].style.fontSize = "30%";

if you need to '!imporant' option

document.getElementsByClassName('B')[0].setAttribute('style', 'font-size: 30% !important');
  • Related