开发者

HTML DOM w3schools clarification

just reading the W3schools HTML DOM tutorial. There's a paragraph that makes no sense to me.

The bit that doesn't make sense to me is:

A common error in DOM processing is to expect an element node to contain text.

However, the text of an element node is stored in a text node.

In this example: <title>DOM Tutorial</title>, the element node <title>, holds a text node with the value "DOM Tutorial".

"DOM Tutorial" is not the value of 开发者_如何学运维the <title> element!

However, in the HTML DOM the value of the text node can be accessed by the innerHTML property.

Ok, what? That sounds exactly the opposite of what I though. Thanks


When a markup document is converted into a DOM, you end up with a tree of nodes.

There are several types of nodes, including elements, text and comments.

Nodes have properties. e.g. an HTMLInputNode will have a value property that maps on to its current value. Any HTMLElementNode will have a style property through which the CSS properties defined via the style attribute can be accessed. Likewise, it will also have a className property that maps onto the class attribute.

When you have <title>DOM Tutorial</title> you have a HTMLTitleNode containing a TextNode. To get the text DOM Tutorial you should access the TextNode and then read its data property.

myTitle.firstChild.data

And then W3Schools muddies the water by mentioning innerHTML.

innerHTML is a property (although not a standard DOM property (I think HTML 5 is in the process of defining it)) of HTMLElementNodes which gives you a serialisation of the HTML contents of an element (but not the element itself).

Since there is only a TextNode inside a title element, you end up with plain text there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜