Live Chat Icon For mobile
Live Chat Icon

How do you get the target element onclick event in Blazor?

Platform: Blazor| Category : Event handling, Tips and Tricks

Blazor does not have support to manipulate DOM elements directly, but we can still achieve it by using JavaScript interop. By creating a reference to an element, we can send it as a parameter to the JavaScript method via interop. In that JavaScript method, we can manipulate the DOM elements.

window.setElementText = (element, text) => {
    element.innerText = text;

Refer the script file in HTML page

 <script src="~/script.js"></script>

@page "/counter"

@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime


<p>Current count: @currentCount</p>

<p>Last button clicked: @lastButtonClicked</p>

<button @ref=button1 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button1))">Click me</button>
<button @ref=button2 class="btn btn-primary" @onclick="@(()=>IncrementCount1(@button2))">Click me</button>

@code {

    private ElementReference button1;
    private ElementReference button2;

    private int currentCount = 0;
    private string lastButtonClicked = "None";

    private async void IncrementCount(ElementReference element)
        lastButtonClicked = "Button 1";
        await JSRuntime.InvokeVoidAsync("setElementText", element, "Button 1 was clicked");

    private async void IncrementCount1(ElementReference element)

            lastButtonClicked = "Button 2";
            await JSRuntime.InvokeVoidAsync("setElementText", element, "Button 2 was clicked");

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.