Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'tagName' does not exist on type ChildNode [Typescript]

Tags:

typescript

I am looping over childNodes from a parent node. I want to access the tagName of the child nodes, but error is tagName doesn't exist on type 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)

It works with 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))
like image 830
Caleb Taylor Avatar asked Nov 07 '19 05:11

Caleb Taylor


1 Answers

childNodes can contain non-element nodes, use children instead.

It works in JavaScript because JS isn't type safe and your parent node happened to only have elements as children (or it printed undefined).

like image 114
Motti Avatar answered Sep 19 '22 00:09

Motti