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");
}
You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s). Warning: This is a live HTMLCollection . Changes in the DOM will reflect in the array as the changes occur.
The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With