Question

I have a span with the id of mySpan. I am trying to change the font-size of it via jquery like this:

$("#mySpan").css("font-size", "50px");

I have also tried this

$("#mySpan").css("font-size", 50+"px");

But nothing happens, I can change the color of the span like this:

$("#mySpan").css("color","#ff0000");

What am I doing wrong?

Was it helpful?

Solution

Your code is ok, as for the problem, I will go in a wild guess (not so wild actually), that you have another value that overwrites it (for example a class with font-size: xxPx !important), or a child element with font-size defined, etc.

Also Anoop Joshi has a good point. That may be also an issue.

Another possibility would be a broken mark-up (like 2 elements with same id - #mySpan). In this case, the selector would return only the first one, and modify it's font, while leaving the second unchanged.

OTHER TIPS

Its working fine. Try to give it in document.ready

 $(document).ready(function () {
        $("#mySpan").css("font-size", "50px");
    });

Pretty sure the only reason the top one wouldn't work there is because its being overwritten by some other CSS Style..

Try this:

 $("#mySpan").css("font-size", "50px !important;");

the keyword important will force this to use instead of some other css that is overwriting your change.

UPDATE: Didn't know that (.css doesnt support important) so instead going to put it in a class and add class to myspan:

CSS:

.fontSizeFifty
 {  font-size: 50px !important; }

JQuery:

$('#mySpan').addClass('fontSizeFifty');

This should resolve your issue, but I'd much rather have more information and do it in a more correct manner...

var mySpan = $("#mySpan")[0]
var style = mySpan.style;
style += (style != "" ? ";" : "") + "font-size:50px !important;";
mySpan.style = style;

That will append the new font size directly into the style tag of the selected element, along with !important, which should override any styles anywhere else.

This is ugly and I'd never use it myself if there were any other way. Finding and fixing the originally applied style would be a better way, but if that's not possible then you have this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top