user111111 user111111 - 2 months ago 30
TypeScript Question

Angular2 returning node instead of Element

export class AppComponent {
title = 'Dashboard';
navbarmenu = NAVBAR;

constructor(router:Router){
router.events.subscribe((event: NavigationEvent) => {
if(document.querySelector('.a-active')) document.querySelector('.a-active').classList.remove('a-active');
});

setTimeout(() => {
let testTry = document.querySelector('.submenu li a.is-active');

if(testTry){
let anchor = testTry.parentNode.parentNode.parentNode.children[0];

// anchor is a node and throwing an error.

anchor.classList.add('a-active');
}
}
}
}


Error: Property 'classList' does not exist on type 'Node'

I can't start my server if this setTimeout function is not commented. But when the server is running and uncomment. It runs properly but still get an error.

Thanks. Any help would be appreciated.

Answer
setTimeout(() => {
    let isActive = document.querySelector('.submenu li a.is-active')

    if(isActive) isActive.closest('ul').closest('li').children[0].classList.add('a-active')
})

Try this workaround! I am not sure why it returns node. In plain javascript, your code should work. Maybe it's a bug on typescript.

Polyfill: http://stackoverflow.com/a/24107550/6741739 or https://github.com/jonathantneal/closest

Notify me if it worked or not.