I'm trying to set the font-family
property using the JQuery css
method and running into a problem when the font name has a space.
No matter how I quote or don't quote the font name, the element ends up like:
<h1 style="font-family: "Comic Sans"">Title Text</h1>
with nested double quotes.
var font_family = 'Arial Black';
var $title_template = $('<h1>Title Text</h1>');
var $title;
console.log(font_family)
$title = $title_template.clone().css({'font-family': font_family});
$('body').append($title)
font_family = "'Arial Black'";
console.log(font_family);
$title = $title_template.clone().css({'font-family': font_family});
$('body').append($title)
font_family = '"Arial Black"';
console.log(font_family);
$title = $title_template.clone().css({'font-family': font_family});
$('body').append($title)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 style="font-family: 'Arial Black'">Title Text</h1>
If you are looking at the font in the developer options in your browser, don't be alarmed that it looks like poorly nested quotes: <h1 style="font-family: "Arial Black"">Title Text</h1>
. That's just how the browser chooses to render the Style property of that element. The style is actually being applied, and the font family is being set properly.
If you look at the properties of the DOM element (in Chrome DevTools for example), you'll see that the value of font-family is "Arial Black"
. The extra quotes are there because of the space in the font name. And if you change the first line of your JS from var font_family = 'Arial Black
to var font_family = 'Arial'
, the value of font-family will appear simply as Arial
(without quotes).
PS - To get "Comic Sans" to appear I had to use "Comic Sans MS", the proper name of the infamous font.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments