Property 'querySelector' does not exist on type 'Node'.


这个是我的代码


 <!DOCTYPE html>
<html>
<head lang="zh-CN">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title></title>
</head>
<body>
    <div id="container">
        <div id="box"></div>
    </div>
    <script src="test.js"></script>
</body>
</html>

这个是test.ts文件


 var box = document.querySelector('#box');
console.log(box.parentNode.querySelector('#box'));

额,这行代码有问题:


 Error:(2, 28) TS2339: Property 'querySelector' does not exist on type 'Node'.

但是我发现 MDN 的文档有如下说明

parentNode is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node.

然后我又进行了如下测试


 var ul = document.querySelector('ul')
undefined
ul.parentNode.toString()
[object HTMLDivElement]"

好吧,parentNode返回的类型不是Node,拿这个报错又是怎么回事
typescript的版本是1.4

typescript JavaScript

僕等がいた 10 years, 2 months ago

HTMLDivElement继承自Node 也能用querySelector吧

午夜前三分钟 answered 10 years, 2 months ago

Your Answer