user203687
user203687

Reputation: 7247

How can I apply some style to JavaScript's "node" object

Imagine that I have a couple of statements as following:

var n1 = oDiv.firstChild;
var n2 = oDiv.lastChild.previousSibling.firstChild; //know this crazy, but for knowledge sake

How can I apply various styles like the following (which usually works only for "element" types and not "node" types):

//does not work
n1.style.borderWidth = "1px";
n1.style.borderColor = "#336699";
n2.style.borderStyle = "solid";

Also, is there any way to typecast "node" to "element" in JavaScript?

update:

The code I am trying to accomplish above is here http://jsfiddle.net/anthachetta/4mXrd/

Upvotes: 4

Views: 4604

Answers (2)

slebetman
slebetman

Reputation: 114094

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:

  1. Standards compliant browsers also count whitespace as nodes.
  2. 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.

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227310

There are a few problems.

What is with the lastChild.previousSibling.firstChild mess? All that's doing is confusing you.

That mess of properties is returning you a text node, not an element.

lastChild gives you "a line", previousSibling gets the <i> tag, then firstChild returns "just". You are trying to apply a style to a text node, which you can't do, you need to style an element.

You are trying to apply the style to the nodeValue. That's a string. You can use parentNode to get to the <i> tag from the text node.

oDiv.lastChild.previousSibling.firstChild.parentNode.style.color = "#FF0000";

DEMO: http://jsfiddle.net/NTICompass/4mXrd/2/

Upvotes: 1

Related Questions