Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select element by class name in typescript?

Tags:

typescript

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");
}
like image 971
kero Avatar asked Jul 10 '16 13:07

kero


People also ask

Can we get element by class?

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.

What JavaScript method should you use if you want to find elements by class name?

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.


Video Answer


1 Answers

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");
}
like image 79
Nitzan Tomer Avatar answered Oct 19 '22 04:10

Nitzan Tomer