In Chrome, style.fontFamily doesn't work for a barcode font, but className does

166 views Asked by At

Consider the following html:

<style>
.barcode { font-family: 'BC C39 3 to 1 Medium'; }
</style>
<div><span id='spn'>1234567</span></div>

The following will set the font to a barcode:

<script>
document.getElementById('spn').className = 'barcode';
</script>

But The following won't:

<script>
document.getElementById('spn').style.fontFamily = 'BC C39 3 to 1 Medium';
</script>

Why?

I need to use the style.fontFamily tag, not the className, but this appears to not be possible for some reason.

1

There are 1 answers

0
t.niese On

I know you already got your answer. But here some explanation why:

If you write fontFamily = 'BC C39 3 to 1 Medium'; then this equals writing:

.barcode { font-family: BC C39 3 to 1 Medium; }

On MDN: Valid family names you have this paragraph:

Font family names must either be given quoted as strings, or unquoted as a sequence of one or more identifiers. This means that punctuation characters and digits at the start of each token must be escaped in unquoted font family names.

So your font name - if written without quotes - is not valid due to the 3 and 1, if it is not surrounded by quotes. The same is true if you use style.fontFamily which is why it has to be:

document.getElementById('spn').style.fontFamily = "'BC C39 3 to 1 Medium'";

Or why 3 and 1 would need to be escaped (but using quotes is the recommended way).