Akin Dönmez
Akin Dönmez

Reputation: 363

trying to find an Element on DOM with typescript

I m totally newbie in typescript. I m just trying to find an element with a selector. whatever i tried findElement() method is always turning undefined. Where am i doing wrong ? Any help greatly appreciated !

var cdnBasePath: any = this.findElement('meta[name="cdnBasePath"]').attr('content');

public findElement(selector: any) {

            if (angular.isDefined(this.$window.jQuery)) {
                return this.$document.find(selector);
            } else {
                return angular.element(this.$document.querySelector(selector));
            }

        }

Upvotes: 1

Views: 3286

Answers (1)

Amid
Amid

Reputation: 22372

In order for "this" to be defined you have to declare your findElement as a instance method of some class. Like this:

class SomeClass
{
    public SomeMethod() 
    {
        var cdnBasePath: any = this.findElement('meta[name="cdnBasePath"]').attr('content');
    }

    public findElement(selector: any) 
    {
        if (angular.isDefined(this.$window.jQuery)) {
            return this.$document.find(selector);
        } else {
            return angular.element(this.$document.querySelector(selector));
        }
    }
}

Otherwise you can have it as static method:

class UI
{
    public static findElement(selector: any) 
    {
            if (angular.isDefined(this.$window.jQuery)) {
                return this.$document.find(selector);
            } else {
                return angular.element(this.$document.querySelector(selector));
            }
    }
}

var cdnBasePath: any = UI.findElement('meta[name="cdnBasePath"]').attr('content');

Or just drop 'this' and have it as global function (I do not recommend this)

function findElement(selector: any) 
{
    if (angular.isDefined(this.$window.jQuery)) {
        return this.$document.find(selector);
    } else {
        return angular.element(this.$document.querySelector(selector));
    }
}

var cdnBasePath: any = findElement('meta[name="cdnBasePath"]').attr('content');

Hope this helps.

Upvotes: 1

Related Questions