次のコードがあります: 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>
そしてtsファイル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'.
私は次の文章を見つけました翻訳
parentNode は現在のノードの親です。要素の親は、Element ノード、Document ノード、または DocumentFragment ノードです。
これが私のテストです
var ul = document.querySelector('ul')
undefined
ul.parentNode.toString()
[object HTMLDivElement]"
何が問題なのか誰か教えてもらえますか?
タイプスクリプトのバージョンは1.4です
ベストアンサー1
TypescriptとJSXを使用したソリューションを探している人(.tsx):
const box = document.querySelector('#box');
console.log((box.parentNode as HTMLElement).querySelector('#box'));