Reputation: 85
I am having troubles with formatting basic javascript output. Right now it is outputting in the generic times font, and I would like to change that to something like calibri.
Example:
var x = document.getElementById("textbox1").value;
document.print("<p style='font-family:calibri'>x</p>");
I'm aware that this doesn't work because it's treating it as a string literal and just outputs an x in calibri font. So how can I get it to output the variable x and keep the font formatting?
Must stay in javascript and html, can use CSS but am not very familiar at all with it.
Upvotes: 0
Views: 4111
Reputation: 1644
The reason it's being treated as a string literal is because it is one.
var x = document.getElementById("textbox1").value;
document.print("<p style='font-family:calibri'>x</p>");
If you want the #textbox's value to appear you'll need this:
var x = document.getElementById("textbox1").value;
document.print("<p style='font-family:calibri'>"+x+"</p>");
Basically, that ties the three strings together, as + is an operator that not only will calculate
alert(1 + 1)
Which would come out as the integer 2
But also
'Hi.'+" I'm Jeff."
Which would come out as the string "Hi. I'm Jeff."
Upvotes: 2
Reputation: 66324
You don't need to use String concatenation at all to achieve this as you want to set the text contents of an element to exactly the String you've obtained
In your StyleSheet (i.e. between <style>
and </style>
),
.some_awesome_description {
font-family: calibri;
}
The .
before the token here specifies "look for this in the class attribute"
In your JavaScript,
// get your String
var x = document.getElementById("textbox1").value;
// create a new element
var my_awesome_element = document.createElement('span');
// set it's text as the String
my_awesome_element.textContent = x;
// set it's class to be matched by the CSS
my_awesome_element.setAttribute('class', 'some_awesome_description');
// append it to the DOM tree where you want it
document.body.appendChild(my_awesome_element);
Things we used
document.createElement
to create a new elementnode.textContent
to set the text of an elementelement.setAttribute
to create an attribute on an elementnode.appendChild
to add an element to the DOM treedocument.body
, the standard way to reference the <body>
of a HTML #document<span>
, a generic inline container elementUpvotes: 1
Reputation: 9157
Separate the x
from the strings with your <p>
and concatenate (+
):
var x = document.getElementById("textbox1").value;
document.write("<p style='font-family:calibri'>" + x + "</p>");
Upvotes: 0