The error message 'tagName' is not a valid property for type ChildNode in Typescript

When I loop over childNodes from a parent node, I encounter an issue while trying to access the tagName of the child nodes. The error message states that tagName does not 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)

This code snippet works perfectly fine 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.779H 6.667V13.666H 8.222v4.667H 9.778 V12.111H3.556Zm7.778-6.223v7.779h3.111V18.334h3.111V12.111Zm3.111,1.556H 16v3.112H14.444Zm4.667-1.556v6.223 h3.111V13.666h 1.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))

Answer №1

childNodes can actually contain a mix of different nodes, including non-element nodes. To avoid unexpected results, it's recommended to use the children property instead.

This behavior in JavaScript is possible because of its lack of type safety. If your parent node only had elements as children, you may not have encountered any issues (or seen 'undefined' printed).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Using interfaces for typecasting in TypeScript

Consider the code snippet below: let x = { name: 'John', age: 30 } interface Employee { name:string, } let y:Employee = <Employee>x; console.log(y); //y still have the age property, why What is the reason for TypeScript ov ...

Is it possible for input properties of array type to change on multiple components in Angular 9?

Encountering an interesting issue that I need clarification on. Recently, I developed a compact Angular application to demonstrate the problem at hand. The puzzling situation arises when passing an Array (any[] or Object[]) as an @Input property to a chil ...

Intellisense capabilities within the Gruntfile.js

Is it a feasible option to enable intellisense functionality within a Gruntfile? Given that 'grunt' is not defined globally but serves as a parameter in the Gruntfile, VSCode may interpret it as an unspecified function parameter 'any'. ...

Using styled-components in React

I came across this interesting code snippet in the styled-components documentation. Here it is: const Button = styled.button<{ $primary?: boolean; }>` background: ${props => props.$primary ? "#BF4F74" : "white"}; color: ${p ...

What is the best way to access data in a node.js application from IONIC typescript via a REST API?

Here is the structure of my service.ts: import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/http'; import 'rxjs/add/operator/map'; /* Generated class for the PeopleSearch provider. See http ...

Error message: "An issue has been encountered within Angular 4 where it is

Thank you for any assistance, I realize this may be a beginner question... but I seem to be missing something and my TypeScript code is error-free. My goal is simple: I want to track which Main Menu Item is currently selected. To achieve this, I have bou ...

Setting options using the form group in dropdowns in Angular can greatly enhance the user experience

I have created a FormGroup called holidayform and set it up as follows: holidayform: FormGroup; this.holidayform = this.fb.group({ title: ['', [Validators.required]], entryDate: ['',], }) this.holidayform.patchValue ...

Preserving the most recent choice made in a dropdown menu

Just started with angular and facing an issue saving the select option tag - the language is saved successfully, but the select option always displays English by default even if I select Arabic. The page refreshes and goes back to English. Any assistance o ...

Unable to access or modify properties within a function passed as an argument

deleteDialog(item, func: Function) { this.dialogService .open(ConfirmDialogComponent, { context: { title:"Are you sure?", cancelClss: "info", confirmClss: "danger", }, ...

Lack of Intellisense in Sveltekit for the generated $types module on WebStorm

Is there a setting in WebStorm to enable intellisense for automatically generated ./$types by SvelteKit? I'm writing without any minimal example, just curious. Everything is done according to SvelteKit's documentation. Using satisfies LayoutLoad ...

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

No contains operator found in Material UI Datagrid

While working on a project, I utilized Material UI's datagrid and successfully implemented filters such as contains and isEmpty. However, I am struggling to find information on how to create a notContains filter. Does Material UI natively support this ...

Having trouble compiling my Angular application with success

I am working with a file named mock-values.ts. In this file, I have defined the following constants: export const TIMES: Time[] = [ { i: '8:00', v: '8' }, { i: '8:30', v: '8:30' }, { i: '9:00', v: &apo ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...

Error occurs when attempting to instantiate a class with parameters that do not match any available constructor signatures

I am attempting to encapsulate each instance of router.navigateByUrl within a class function, with the intention of calling that function in the appropriate context. However, I am encountering an error that states 'Supplied parameters do not match any ...

What could be the reason for the tsc command not displaying compilation errors when compiling a particular file?

My file, titled app.ts, contains the following code snippet: interface Foo { bar:String; } const fn = (foo? :Foo) => foo.bar; When I run tsc from the root folder with strict:true in my tsconfig.json file, I receive an error message like this ...

Console.log is displaying array as [object Object] when utilizing Typescript

When working with an object in typescript called "obj," I encountered a strange behavior. Initially, when I ran the console.log(obj); command, the output in the terminal console was displayed as [object Object]. However, after wrapping it in JSON.stringify ...

When incorporating leaflet-routing-machine with Angular 7, Nominatim seems to be inaccessible

Greetings! As a first-time user of the Leafletjs library with Angular 7 (TypeScript), I encountered an error while using Leaflet routing machine. Here is the code snippet that caused the issue. Any ideas on how to resolve this problem? component.ts : L. ...

When a const variable is declared within the composition-api setup(), it remains unchanged unless redeclared within the function scope

Being primarily a back-end developer, the front-end side of things is still relatively new to me. I'm aware that there are concepts in this domain that I haven't fully grasped yet, and despite my efforts, I'm unable to resolve a particular i ...