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
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.
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.
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.
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
)
Use a type assertion as shown:
var box = document.querySelector('#box');
console.log((<Element>box.parentNode).querySelector('#box'));
For those looking for a solution using Typescript and JSX:
const box = document.querySelector('#box');
console.log((box.parentNode as HTMLElement).querySelector('#box'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With