Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following code: test.html

<!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>

and the ts file test.ts

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

and i got the error.

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

I found the following sentence in 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.

here is my test

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

could someone tell me what's wrong with that?

the version of typescript is 1.4

like image 947
再见田园犬 Avatar asked Jul 06 '15 03:07

再见田园犬


People also ask

Does not exist on type element typescript?

The error "Property 'X' does not exist on type 'Element'" occurs when we try to access a property that doesn't exist on an element of type Element . To solve the error, use a type assertion to type the element correctly before accessing the property. This is the index. html file for the examples in this article.

How do I know if querySelector exists?

To check if an element does not exist in the DOM: Use the getElementById or querySelector methods to select the element. Check if the stored value is equal to null . If the value is equal to null , the element does not exist in the DOM.

How do I find querySelector?

Document.querySelector() The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.


2 Answers

could someone tell me what's wrong with that

TypeScript's view of the API. At the moment there is no way to say that the type of foo.parentNode depends on the type of foo. Currently it is inferred to always be of type Node and Node does not contain the API querySelector (available on Element)

Fix

Use a type assertion as shown:

var box = document.querySelector('#box');
console.log((<Element>box.parentNode).querySelector('#box'));
like image 58
basarat Avatar answered Sep 20 '22 16:09

basarat


For those looking for a solution using Typescript and JSX:

const box = document.querySelector('#box');
console.log((box.parentNode as HTMLElement).querySelector('#box'));
like image 26
connexo Avatar answered Sep 17 '22 16:09

connexo