0

Is there a way to apply a CSS style within Javascript?

Say I have a CSS style titled "InfoFont" and I want to apply it to the text written from document.write("Information");, how would I do this?

3
  • 7
    document.write("<span class='InfoFont'>Information</span>");, with the normal caveat that document.write should be avoided. Commented Oct 9, 2012 at 19:50
  • I don't feel like expanding on the better alternatives to document.write though :) Commented Oct 9, 2012 at 19:51
  • @MattGreer: +1 for the best comment answer. Post this comment as answer. Commented Oct 9, 2012 at 19:59

3 Answers 3

3

You would need to wrap the content you are adding dynamically with a tag containing the desired CSS class.

Are you really adding content via document.write though?

It would be more common to see something like this:

var newDiv = document.createElement( "div" );

newDiv.className = "InfoFont";
newDiv.innerHTML = "[YOUR CONTENT HERE]";

document.getElementById( "[RELEVANT CONTAINER ID]" ).appendChild( newDiv );
Sign up to request clarification or add additional context in comments.

1 Comment

Don't use .setAttribute("class"). There are IE issues. Use newDiv.className = ... instead.
2

You need a document element like a span or a div to encapsulate your text. Then, you can apply a style to the encapsulating element.

As the comment mentioned, you should be avoiding document.write. I recommend you use jquery or another framework to manipulate the DOM if you have access to them.

Comments

1

Try this way:-

var ele = document.createElement('div');
ele.setAttribute('id', 'ELEMENTID');
ele.setAttribute('className', 'InfoFont'); // OR  ele.className = 'InfoFont';
ele.innerHTML = "CONTENT";

@Matt's comment answer is the simply best answer.

1 Comment

@Matt's comment answer is the simply best answer. If you leave out the undesirability of using document.write to add content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.