The DOM works exactly the same way as HTML does. That makes sense since the DOM was designed to model HTML as objects. So, what do you do if you want to make the following bold:
Hello World
From your code, what you're trying to do is something like this:
style=font-weight:bold Hello World
Obviously that wouldn't work because it's not valid HTML. What you'd normally do is this:
<span style='font-weight:bold;'>Hello World</span>
So you need to do the same in the DOM:
// Assume you have a div "div" and the first child
// is the text node "Hello World"
var hello_world = div.firstChild;
// Now, you want to make Hello World bold.
// So you need to create a span:
var span = document.createElement('span');
span.style['font-weight'] = 'bold';
// Now wrap hello_world in the span:
span.appendChild(div.removeChild(hello_world));
The above is actual working DOM code that does what you want. But beware:
- Standards compliant browsers also count whitespace as nodes.
- IE doesn't count whitespace as nodes.
For example, if your HTML looks like this:
<div>
<span>Hi</span>
</div>
the standard says your DOM must look like this:
div +
|---- text node (whitespace)
'---- span +
'---- text node (Hi)
but IE does what most people probably expect:
div +
'---- span +
'---- text node (Hi)
This means that you can't blindly trust node.firstChild
without checking to see if it's what you expect.