HTML DOM w3schools 澄清
刚刚阅读 W3schools HTML DOM 教程。有一段对我来说毫无意义。
对我来说没有意义的一点是:
DOM 处理中的一个常见错误是期望元素节点包含文本。
但是,元素节点的文本存储在文本节点中。
在此示例中:
,元素节点
DOM Tutorial
</code> 保存一个值为“DOM Tutorial”的文本节点”。</p> <p>“DOM 教程”<strong>不是</strong> <code><title></code> 元素的值!</p> <p>但是,在 HTML DOM 中,可以通过innerHTML 属性访问文本节点的值。</p>
好吧,什么?这听起来与我的想法完全相反。 谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当标记文档转换为 DOM 时,您最终会得到一棵节点树。
节点有多种类型,包括元素、文本和注释。
节点具有属性。例如,HTMLInputNode 将具有映射到其当前值的
value
属性。任何 HTMLElementNode 都会有一个style
属性,通过该属性可以访问通过style
属性定义的 CSS 属性。同样,它还有一个映射到class
属性的className
属性。当您有
DOM Tutorial
时,您就有了一个包含 TextNode 的 HTMLTitleNode。要获取文本DOM Tutorial
,您应该访问 TextNode,然后读取其data
属性。然后 W3Schools 又提到了
innerHTML
,把水搅浑了。innerHTML
是 HTMLElementNodes 的一个属性(尽管不是标准 DOM 属性(我认为 HTML 5 正在定义它)),它为您提供元素的 HTML 内容的序列化(但不是元素本身)。由于标题元素内只有一个 TextNode,因此最终会得到纯文本。
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 astyle
property through which the CSS properties defined via thestyle
attribute can be accessed. Likewise, it will also have aclassName
property that maps onto theclass
attribute.When you have
<title>DOM Tutorial</title>
you have a HTMLTitleNode containing a TextNode. To get the textDOM Tutorial
you should access the TextNode and then read itsdata
property.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.