normalize (W3C DOM Core method)
| Version | Depr. | Static |
|---|---|---|
| DOM2 | No | No |
| IE6+ | FF1.5+ | SA1.3+ | OP9+ |
|---|---|---|---|
| Buggy | Full | Full | Full |
- Returns
void
Example
node.normalize();
The example above will normalize the sub-tree underneath
node.
Arguments
No arguments
Description
Puts this node's sub-tree in a
state whereby only structural nodes separate Text
nodes.
When a document is first loaded there will be only one
Text node for each block of text. Operations such as
splitText may divide blocks of text into
multiple sibling Text nodes, as may creating and
adding new Text nodes, but such divisions will not
persist between sessions. The normalize method merges
adjacent nodes to [re]create the load state of a single
Text node for each block of text.
However this operation doesn't remove whitespace-only Text nodes, because they're not empty — they contain
whitespace, and although whitespace is usually insignificant, an
implementation should not presume that.
Therefore even a normalized node may have a different subtree between browsers — for example, Firefox counts whitespace-only text nodes as part of the DOM, whereas Internet Explorer ignores them. To gain a truly uniform DOM you can use a whitespace stripping method, such as this one by Alex Vincent:
function cleanWhitespace(node)
{
for (var i=0; i<node.childNodes.length; i++)
{
var child = node.childNodes[i];
if(child.nodeType == 3 && !/\S/.test(child.nodeValue))
{
node.removeChild(child);
i--;
}
if(child.nodeType == 1)
{
cleanWhitespace(child);
}
}
return node;
}
The example above will remove all text nodes that only contain whitespace, making the sub-tree underneath node consistent between browsers, and can be called like this:
cleanWhitespace(node);
So if we started with this HTML:
<blockquote class="yoda">
<p>
When nine-hundred years old you reach,
look as good you will not!
</p>
</blockquote>
Running cleanWhitespace on the
<blockquote> element would produce this
result:
<blockquote class="yoda"><p>When nine-hundred years old you reach, look as good you will not!</p></blockquote>
Compatibility
| Internet Explorer | Firefox | Safari | Opera | |||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 5.5 | 6.0 | 7.0 | 1.5 | 2.0 | 3.0 | 1.3 | 2.0 | 3.0 | 9.0 | 9.5 |
| None | Buggy | Buggy | Full | Full | Full | Full | Full | Full | Full | Full |
Internet Explorer 5.5 doesn't implement this method, and will throw an error if it's used.
It has been reported that this method can cause some early versions of Internet Explorer 6 to crash. However since I can’t replicate confirm this, it is not documented as a known bug.
User-contributed notes
Add a note
To post a note on this topic, please log in with your SitePoint username and password. If you don't have an account yet, you can create a new account for free.