Typescript: Property 'classList' does not exist on type 'Node & ParentNode'

Created on 17 May 2020  路  4Comments  路  Source: microsoft/TypeScript

Hi, I'm getting this error

ts(2339) Property 'classList' does not exist on type 'Node & ParentNode'.

on something that does have a classList. There's a workaround at the end.

TypeScript Version: 3.7.x-dev.201xxxxx


Search Terms:

  • classList not exist node
  • parentNode classList
  • classList

Code

// TS says the type of elem is Element
const elem = document.querySelector( '#parent > .child' );

// This is ok
elem.classList.add( 'a-class' );

// TS says the type of elem.parentNode is Node & ParentNode
// This fails
elem.parentNode.classList.add( 'another-class' );

Expected behavior:
To actually pass type checking.

Actual behavior:

Type checking fails with message
TS2339: Property 'classList' does not exist on type 'Node & ParentNode'.

Similar issues

Saw around the web other similar issues like _Property 'querySelector' does not exist on type 'Node'_

Workaround

I had to do this to pass type checking.

(<Element>elem.parentNode).classList.add( 'another-class' );
Question

Most helpful comment

Just guessing, but could this be because the parentNode of an 'html' element is a Document, which doesn't have a classList? So the general statement elem.parentNode.classList.add could thrown, depending on what 'elem' refers to.

All 4 comments

Just guessing, but could this be because the parentNode of an 'html' element is a Document, which doesn't have a classList? So the general statement elem.parentNode.classList.add could thrown, depending on what 'elem' refers to.

In this case, child was an <a>, parent an <li>. Both have classList.

Sure, but tsc can't statically know that. It would have to have deep understanding of the CSS selector '#parent > .child'.

This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yortus picture yortus  路  157Comments

tenry92 picture tenry92  路  146Comments

chanon picture chanon  路  138Comments

xealot picture xealot  路  150Comments

disshishkov picture disshishkov  路  224Comments