Questions & Answers

TS2339: Property 'style' does not exist on type 'Element'?

Here's the code:

ngOnInit() {
const navSlide = () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav-links');
  const navLinks = document.querySelectorAll('.nav-links li');
  burger.addEventListener('click', () => {
  navLinks.forEach((link, index) => { = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;


Error I get when compiled:

Property 'style' does not exist on type 'Element'.ts(2339)

How can I fix it?

2023-01-25 09:42:03
Can you provide a reproducible example? Also you should be using ViewChild to get references to your elements, as it is the way angular intends it for you to get references to dom elements.
2023-01-25 09:42:03
@MikeS. - The above is reproducible if you take the body of navSlide and put it in the playground:…
2023-01-25 09:42:03
@MikeS. - The Angular part of your comment could be the basis for a good answer, though, IMHO.
2023-01-25 09:42:03
Answers(2) :

querySelectorAll returns a NodeList known to contain Elements, but not specifically HTMLElements. In your case, you know that these are HTMLElements (specifically HTMLLIElements), so you can use a type assertion saying that:

navLinks.forEach((link, index) => {
    (link as HTMLElement).style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;

But see Mike S.'s comment - I don't do Angular, but it sounds like there's a more Angular-specific solution here.

2023-01-25 09:42:03
Yep, my bad. I didn't quite read the error message. This will work, except you'll have to use the life-cycle hook ngAfterViewInit instead of ngOnInit, as the view is only initialized then.
2023-01-25 09:42:03
Great! It Works. Thanks @ T.J. Crowder
2023-01-25 09:42:03
working perfectly for me. ty

As T.J. said the NodeList returns NodeList of Element, another solution is type the QuerySelectorAll by yourself.

const navLinks = document.querySelectorAll<HTMLElement>('.nav-links li');