乐闻世界logo
搜索文章和话题

How to check tagName in eventTarget using Typescript?

1个答案

1

When using TypeScript, to check the tag name within an EventTarget (typically referring to the HTML element's tag name), you can access the tagName property of the event target. The tag name (tagName) is a read-only property that returns the element's tag name, typically in uppercase.

Here is a specific example demonstrating how to check the tag name of the clicked element in a click event:

typescript
// HTML section <button id="myButton">Click me</button> // TypeScript section // Get the button element const button = document.getElementById('myButton'); // Add a click event listener button?.addEventListener('click', (event) => { // event.target represents the element that triggered the event // Assert event.target as HTMLElement type to allow TypeScript to recognize the tagName property const target = event.target as HTMLElement; // Check tagName if (target.tagName === 'BUTTON') { console.log('Button clicked!'); } else { console.log('Not a button, but:', target.tagName); } });

In this example, we first retrieve the button element from the page and add a click event listener to it. When the button is clicked, the event handler is triggered. We obtain the element that triggered the event via event.target and cast it to HTMLElement type, enabling TypeScript to recognize the tagName property. Then, we check if tagName is 'BUTTON' to determine if the clicked element is a button. If it is a button, we output the corresponding message; otherwise, we output the tag name of the clicked element. This approach can be used in various scenarios, such as when you want to respond differently to elements of different types or when you need to filter out elements that should not trigger events. By checking tagName, you can flexibly control the logic of event handling.

2024年7月23日 15:36 回复

你的答案