【问题标题】:Property 'tagName' does not exist on type ChildNode [Typescript]ChildNode [Typescript] 类型上不存在属性“tagName”
【发布时间】:2019-11-07 18:43:21
【问题描述】:

我正在从父节点循环子节点。我想访问子节点的 tagName,但错误是 tagName 在 ChildNode 类型上不存在。

const contentParsed = new DOMParser().parseFromString(content, 'text/xml');
const svgBody = contentParsed.querySelector('svg');

if (svgBody === null) throw new Error('content must be svg');
svgBody.childNodes.forEach((node) => node.tagName) // Property 'tagName' does not exist on type 'ChildNode'.ts(2339)

它适用于 javascript

const svgStr = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><title></title><path d="M 2.6846088,10.906645 H 28.979394 v 8.389403 H 15.580319 l -0.719092,1.438183 -3.811186,0.143819 -0.575273,-1.582002 H 2.6846088 Z" fill="#fff"/><path d="M2,10.555H30v9.335H16v1.556H9.778V19.889H2Zm1.556,7.779H6.667V13.666H8.222v4.667H9.778V12.111H3.556Zm7.778-6.223v7.779h3.111V18.334h3.111V12.111Zm3.111,1.556H16v3.112H14.444Zm4.667-1.556v6.223h3.111V13.666h1.556v4.667h1.556V13.666h1.556v4.667h1.556V12.111Z" fill="#cb3837"/></svg>`
const contentParsed = new DOMParser().parseFromString(svgStr, 'text/xml');
const svgBody = contentParsed.querySelector('svg');

if (svgBody === null) throw new Error('content must be svg');
svgBody.childNodes.forEach(node => console.log(node.tagName))

【问题讨论】:

    标签: typescript


    【解决方案1】:

    childNodes 可以包含non-element nodes,请改用children

    它可以在 JavaScript 中工作,因为 JS 不是类型安全的,而且您的父节点碰巧只有元素作为子节点(或者它打印了 undefined)。

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 2021-11-30
      • 2023-04-02
      • 2018-08-17
      • 1970-01-01
      • 2023-02-06
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多