Leonardo Faitão Leonardo Faitão - 9 months ago 490
Javascript Question

TypeScript - How to get an HTML element like using dollar sign ($) in Javascript

I have the following javascript code in my page that get an element with the class ".parallax" and calls the javascript method "parallax()".
Obviously, I need to do this to make the parallax effect to work.


However, once I'm using my HTML elements in the component template in TypeScript file, I need to call it from the TS file.

So how can I get this element by its class name and call the javascript method in Typescript file?

Obs.: I already tried to do this:

var element = <HTMLElement> document.getElementsByClassName('parallax')[1];

But the compiler doesn't recognize the method "parallax()", warning me this:

TS2339: Property 'parallax' does not exist on type HTMLElement


Thank you for your help, @basarat! I followed your tips, but I needed more information to make it work!

My initial problem was to use the $ (dollar) sign, and I solved it by adding this:

import * as $ from 'jquery';

The import above is the right answer to my main question here. However, it was not enough to make the external Javascript function .parallax() to work. I will put below what I did to make ot work whether someone also needs this answer.

I followed some tips from this StackOverflow answer.

Like basarat said, I created a file named parallax.d.ts, but with the following interface:

interface JQuery {

Then referenced both parallax and jquery files to my component landingPage.view.ts file:

///<reference path="../../../typings/browser/ambient/jquery/index.d.ts"/>
///<reference path="../../shared/parallax.d.ts"/>

and then edited my component class to this:

export class AppLandingPage implements AfterViewInit {
    static landingPageInitialized = false;

    constructor(private el:ElementRef) {

    ngAfterViewInit() {
        if(!AppLandingPage.landingPageInitialized) {
            AppLandingPage.landingPageInitialized = true;

Now, by my understanding, the constructor is referencing the component through the el variable, I use this element in jQuery, find the components with the ".parallax" class, and call the function parallax() to make the parallax framework in JS to run.

I'm not sure if I'm explaining everything as it is, but now it works! Hehe

Thank you again for all your help!