Trigger Click in Typescript - Property 'Click' Does Not Exist on Type 'Element'

Trigger click in Typescript - Property 'click' does not exist on type 'Element'

Use the type HTMLElement instead of Element. HTMLElement inherits from Element. And in the documentation you can find that click function is defined in the HTMLElement.

Cast your element into the HTMLElement via

let element: HTMLElement = document.getElementsByClassName('btn')[0] as HTMLElement;
element.click();

Property 'onclick' does not exist on type 'Element'

As the user above mentioned, you have to cast it to HTMLElement, but inside the for loop. I don't have reputation to comment, thats why i answered again.

  ngOnInit() {
const acc = document.getElementsByClassName('accordion');
let i;
for (i = 0; i < acc.length; i++) {
HTMLElement(acc[i]).onclick = function() {
this.classList.toggle('active');
this.nextElementSibling.classList.toggle('show');
};
}
}

Or I would rather recommend using the "addEventListener" function, if you use "document.getElementsByClassName" anyways.

  ngOnInit() {
const acc = document.getElementsByClassName('accordion');
let i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click",function() {
this.classList.toggle('active');
this.nextElementSibling.classList.toggle('show');
});
}
}

Property 'click' does not exist on type 'never'. TS2339

TypeScript can't infer the type of the ref from where you use it later in the code, you have to tell it the type of the ref:

const ref = useRef<HTMLDivElement>(null);
// −−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^

(useRef adds the null type to the type parameter you give it, soyou don't have to use <HTMLDivElement | null>.)

Property 'click' does not exist on type 'DebugElement'

You can use JavaScript selector like this

const button = fixture.debugElement.nativeElement.querySelector('.btnClass');
button.click();

TS2339: Property 'style' does not exist on type 'Element'

You need a typecast:

Array.from(document.getElementsByClassName('mat-form-field-infix') as HTMLCollectionOf<HTMLElement>)

That's because getElementsByClassName only returns HTMLCollection<Element>, and Element does not have a styleproperty. The HTMLElement however does implement it via it's ElementCSSInlineStyle extended interface.

Note that this typecast is typesafe in the way that every Elementis either a HTMLElement or an SVGElement, and I hope that your SVG Elements don't have a class.

querySelector with trigger click not working into angular 2

Your question is missing a lot of details but can you try to explicitly cast it as an HTMLElement:

let yourElem= <HTMLElement>document.querySelector('.class');
yourElem.click();


Related Topics



Leave a reply



Submit