Change font after createTextNode ()

I need to change the font of an element created by the createTextNode () function:

var s = document.createTextNode(item.text); s.setAttribute("font size") = -1; elem.appendChild(s); 

In my code, I get a Firebug error message:

s.setAttribute is not a function

How to change the font of the created element?

+8
javascript dom html
source share
3 answers

You do not specify the font in the text nodes , you do it on the parent element - in your case:

 elem.style.fontSize = "20px"; 

If you do not want to change the font size for the entire parent element, you can create a <span> element to wrap the node text:

 var span = document.createElement('span'); span.style.fontSize = "20px"; span.appendChild(s); elem.appendChild(span); 
+9
source share

createTextNode creates a Text node that has only one method: splitText. setAttribute is a DOM Core method implemented through the Element interface (i.e. not text nodes).

Generally, you should avoid setAttribute, as it has numerous quirks and setting the corresponding DOM property is faster and more reliable.

In any case, there is no fontSize attribute specified in HTML 4.01 for text nodes, so you cannot expect browsers to implement it. Text nodes inherit their style from their parent element, so if you want to set the font size of some text, wrap it in an element:

 window.onload = function() { var span = document.createElement('span'); // Set DOM property span.style.fontSize = '200%'; span.appendChild(document.createTextNode('hey')); // Add to document document.body.appendChild(span); }; 

But in general, you better define the style in the class and attach it to the range.

+1
source share

Perhaps you can use the built-in css. Never tried this with a text box though

 setAttribute('style', 'font-size:-1;'); 
0
source share

All Articles