19

I am trying to design responsive menu bar that collapses in small screens, however, I am using typescript. is there any clue what equivalent to this code in typescript

function myFunction() {
document.getElementsByClassName("topnav")[0].classList.toggle("responsive");}

I changed to this code in typescript but it never works

myFunction(): void {
(<HTMLScriptElement[]><any>document.getElementsByClassName("topnav"))[0].classList.toggle("responsive");
}

1 Answer 1

25

There's no need to change anything because typescript is a superset of javascript, so even regular javascript can be typescript.

With that being said, you can add some typescript features:

function myFunction(): boolean {
    let elements: NodeListOf<Element> = document.getElementsByClassName("topnav");
    let classes: DOMTokenList = elements[0].classList;
    return classes.toggle("responsive");
}

But there's no need to break things apart like that, so you can just have your exact code, but maybe add a return type to the function signature:

function myFunction(): void {
    document.getElementsByClassName("topnav")[0].classList.toggle("responsive");
}

Or

function myFunction(): boolean {
    return document.getElementsByClassName("topnav")[0].classList.toggle("responsive");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.