惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
Engineering at Meta
Engineering at Meta
A
About on SuperTechFans
T
The Blog of Author Tim Ferriss
I
InfoQ
博客园_首页
G
Google Developers Blog
爱范儿
爱范儿
Last Week in AI
Last Week in AI
量子位
阮一峰的网络日志
阮一峰的网络日志
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
月光博客
月光博客
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
N
Netflix TechBlog - Medium
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Opening Pandora's Box: How to Unlock Direct DOM Method Ca...
jsakamoto · 2026-06-13 · via DEV Community

🔰 Referencing and operating DOM elements in Blazor

In Blazor, you can reference a DOM element that a component has rendered by using the ElementReference type.

<input type="text" @ref="_inputElement">...</input>

@code {
    private ElementReference _inputElement;
}

The reference you get this way is handy. You can pass it as an argument when you call a JavaScript function or method from the Blazor side, using the JavaScript interop feature. The ElementReference type also gives you a FocusAsync() extension method, which lets you set focus on the DOM element it points to.


🤔 The limit, and the pain

But what if you want to do more than just setting focus? Say you want to call DOM methods like click, select, or scrollIntoView. Normally, you have to create an external JavaScript file, define a proper function there, and call it from the Blazor side.

Let me show you what that looks like. First, you create a JavaScript file like this.

// wwwroot/js/elementMethods.js
export const scrollIntoView = (element, options) => element.scrollIntoView(options);

Then, to call this function from Blazor, you import the JavaScript module using IJSRuntime and call the function from it.

@inject IJSRuntime JSRuntime
...
<input type="text" @ref="_inputElement">...</input>
...
@code {
    private ElementReference _inputElement;

    private async Task ScrollIntoView()
    {
        await using var module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/elementMethods.js");
        await module.InvokeVoidAsync("scrollIntoView", _inputElement, new { behavior = "smooth" });
    }
}

Honestly, having to create an external JavaScript file just to do a tiny DOM operation is painful. You think, "ah, I just want to scroll to this element," or "I just want to select this element," and then you have to stop and go create a JavaScript file. That breaks your flow every single time.

Sure, these days we often let an AI agent write the code, so maybe this is less of a big deal. But here's the thing: during human code review or quick fixes, jumping back and forth between the .razor and .js files, and keeping the two in sync, is still a real hassle.


🤷 Many Issues raised, all of them closed

This problem is not new. Since 2019, people have opened improvement request Issues to the ASP.NET Core team many times.

2019
#6937 [Blazor] Direct DOM Manipulation with C#

2020
#24734 JSInterop for properties and element methods
#25685 Get IJSObjectReference from ElementReference

2021
#28820 DOM API Bindings and Blazor support
#29823 New properties for ElementReference (SelectAllAsync, GetBoundingRectangleAsync)
#29826 Expose IJSRuntime instance through ElementReference

2023
#47197 Expose internal JSRuntime in ElementReference for static extensions

2024
#61488 Add interop API to ElementReference

And yet, every single one of these Issues was closed with the same answer: "we will not support this." The reasons go something like this:

  • If it becomes too easy to call methods from a DOM element reference, code that touches the DOM directly will grow, and that invites performance problems.
  • It risks breaking Blazor's abstraction layer and damaging the DOM model.

Fair enough. The ASP.NET Core team's reasoning makes sense. But even so, not being able to do even a tiny DOM operation without an external JavaScript file is still tough.


💡 There was a way to call it directly!

Now, here is an interesting fact. In Blazor's JavaScript interop, you can receive a reference to any JavaScript object as an IJSObjectReference on the Blazor side, and then call its methods. And a DOM element in the browser is, from JavaScript's point of view, ultimately just an object too.

So that got me thinking.

If I could convert an ElementReference into an IJSObjectReference without an external JavaScript file, then I could call DOM methods directly, all within the .razor file alone. Right?

I brought this idea to an AI chat, and it told me something neat: "The browser built-in Object() function returns the object you pass to it as is (boxing). So you can use it to convert an ElementReference into an IJSObjectReference." I tried it right away, and it worked beautifully! It almost felt too easy 😅

Here is the code.

@inject IJSRuntime JSRuntime
...
<input type="text" @ref="_inputElement">...</input>
...
@code {
    private ElementReference _inputElement;

    private async Task ScrollIntoView()
    {
        // Pass the ElementReference to JavaScript's Object() function
        // to "convert" it into an IJSObjectReference
        await using var inputJsObj = await JSRuntime.InvokeAsync<IJSObjectReference>("Object", _inputElement);

        // After converting, you can call DOM methods directly without any external .js file!
        await inputJsObj.InvokeVoidAsync("scrollIntoView", new { behavior = "smooth" });
    }
}

With this technique, you can call any method of the referenced DOM element from inside the .razor file alone. No need to create or edit an external JavaScript file. That cuts down a lot of friction when you just want a small DOM operation. You no longer leave the .razor file and travel back and forth to the .js file while you work.


🔍 A related approach

I am not the first to chase this idea. A similar technique, calling DOM element methods from the .razor file alone without an external JavaScript file, was introduced in a nice article back in 2024.

Say goodbye to JavaScript in your Blazor web app | My Reality

Uni is taking too much of my time, and so I cannot work much on Project Reality and lxmonika.

favicon trungnt2910.com

The method in that article does not call the method straight from the DOM element reference. Instead, it goes through the prototype of the HTML element. What you can do is the same in the end. But I think the Object() function approach shown here is shorter and a bit more intuitive to write.


⚠️ Things to watch out for

I really do think this technique, converting an ElementReference into an IJSObjectReference with Object() and calling DOM methods directly, is convenient and useful. Still, I want to be honest about the trade-offs. The ASP.NET Core team kept raising the same concerns in those Issues, and those concerns are real. Careless use can lead to problems like "it was fine in development, but performance dropped in production," or damage to the DOM model from skipping Blazor's abstraction layer.

On top of that, this technique has a few specific points to keep in mind:

  • Compared to the Say goodbye to JavaScript in your Blazor web app method above, it needs one extra JavaScript interop call to do the conversion into IJSObjectReference.
  • If you forget to dispose of the IJSObjectReference, you get a memory leak.
  • After the conversion, even if a re-render changes the target DOM element, the IJSObjectReference keeps pointing at the now detached DOM element.

So please use this only when you are sure it will cause no problem, and do not overuse it. In particular, avoid it in code that may run often, or in code where performance matters. Sharing this technique in custom instructions or skills for your team or your AI agents is a good idea, but I think you should also make the rules for its use clear at the same time.


🎉 Wrap-up

I showed you a technique that converts a Blazor ElementReference into an IJSObjectReference using the browser built-in Object() function. With it, you can call any method of a DOM element from inside the .razor file alone, with no external JavaScript file. Just remember the concerns the ASP.NET Core team raised, and avoid careless overuse.

That said, this little trick is genuinely handy when you want a quick DOM operation. Part of me still wishes the Blazor team would relax this a bit on the official side. But for now, I will happily keep my Blazor development smooth with this workaround.

If you know of other approaches or have updates to share, please drop them in the comments! 👇

❤️ Happy coding!