简体   繁体   English

使用innerHTML和vanilla JS检索节点的内容

[英]retrieving content of a node using innerHTML and vanilla JS

Im trying to learn some key concepts of DOM traversal using vanilla javascript and just generally trying to get my head around some basic concepts ive mostly skipped... There are a few concepts I am not quite understanding. 我试图学习使用香草javascript进行DOM遍历的一些关键概念,并且通常只是想让我绕过一些基本概念,而我主要跳过了这些概念...有些概念我不太了解。

if we take a simple HTML page: 如果我们使用一个简单的HTML页面:

<html>
<head>
<title>hello</title>
</head>
</html>

to my way of thinking I should be able to retrieve the string "hello" using the following: 按照我的想法,我应该能够使用以下方法检索字符串“ hello”:

window.document.head.title.innerHTML;

However this just returns an empty string. 但是,这只会返回一个空字符串。 Can anyone explain why? 谁能解释为什么?

There are several ways of accessing a page's title, some of which you can find below: 有几种访问页面标题的方法,其中一些可以在下面找到:

// search for the node
document.querySelectorAll('title')[0].innerHTML
// with html5
document.querySelector('title').innerHTML
// get by tag name
document.getElementsByTagName('title')[0].innerHTML
// or simply use this
document.title

You can't simply write the name of a specific tag and expect to get the result you want. 您不能简单地写一个特定标签的名称并期望得到想要的结果。 Just because there happens to be only one <title> tag on the entire page doesn't mean that this is a feasible way of accessing any node. 仅仅因为整个页面上只有一个<title>标记并不意味着这是访问任何节点的可行方法。 There are some special cases such as document.head , document.body , and document.title that always refer to certain elements. 有一些特殊情况,例如document.headdocument.bodydocument.title总是引用某些元素。 They don't necessarily follow the DOM structure in the way you expect them to do. 它们不一定按照您期望的方式遵循DOM结构。

document.querySelector('title').innerHTML

这是获取标题文字的正确方法

That is because it is just document.title 那是因为它只是document.title

edit: explanation. 编辑:解释。 That is because, .title returns the title of an element, you are trying to return the .title attribute of the head element, which you never gave it one so it is an empty string 这是因为.title返回元素的标题,而您试图返回head元素的.title属性,而您从未给过它一个,所以它是一个空字符串

<head title="head title"></head>

so document.head.title will return head title 因此document.head.title将返回标题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM