Jeremy
Jeremy

Reputation: 3809

Apply CSS style to text within Javascript?

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?

Upvotes: 0

Views: 532

Answers (3)

Siva Charan
Siva Charan

Reputation: 18064

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.

Upvotes: 1

Kevin Boucher
Kevin Boucher

Reputation: 16675

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 );

Upvotes: 3

Maess
Maess

Reputation: 4146

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.

Upvotes: 2

Related Questions