javascript - PhpStorm/WebStorm 中的 Node 类型中未定义属性 id

标签 javascript dom phpstorm webstorm

Php/WebStorm 在我的 JavaScript 代码中报告了这个奇怪的警告,指出属性 id 未在元素/节点中定义。事实是,该元素是从父元素获取的 firstChild 元素。

function hideChildAndUpdateID(title) {
    let parent = document.getElementById('parent');
    let child = parent.firstChild;

    // Hiding the child.
    child.style.display = 'none';
    // Temporary ID so we can find it later.
    child.id = 'child-tmp-id'; // Warning occurs here
}

这是来自 Php/WebStorm 的完整消息

Property id is not defined in type Node less... (Ctrl+F1) 
Inspection info: This inspection reports assignments to undefined properties of explicitly type-annotated variables.

这段代码本身确实有效。 child 元素将其 id 更改为我设置的任何内容,但此警告让我很恼火。

我尝试过使用 child.setAttribute('id', 'child-tmp-id'),但无法正常工作。

处理 firstChild 时是否有约定,或者它只是一个 Php/WebStorm 的东西?

最佳答案

节点不仅仅是元素,也不一定具有 id 属性。尝试使用 firstElementChild 来返回作为元素的第一个子元素:

function hideChildAndUpdateID(title) {
    let parent = document.getElementById('parent');
    let child = parent.firstElementChild;

    // Hiding the child.
    child.style.display = 'none';
    // Temporary ID so we can find it later.
    child.id = 'child-tmp-id'; 
}

关于javascript - PhpStorm/WebStorm 中的 Node 类型中未定义属性 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55060264/

相关文章:

javascript - 将值从多个对象推送到数组

javascript - 路由中的 Ember "Params is not defined"

javascript - 如何编译我的 TypeScript Phaser 项目,使其仅使用 Phaser.d.ts 引用路径找到 "Phaser"命名空间?

PHPDoc - 函数退出

PhpStorm:如何判断数组成员的 var 类型?

javascript - 如何获取等于 10 的输入并执行在屏幕上显示“awesome”的功能

javascript - 火狐扩展 : how to get a script to run from a load overlay

jquery - 遍历这个 DOM 段的更好方法

JavaScript,循环所有选择?

javascript - 功能超出范围?