Blazor doesn’t manipulate the DOM directly at C# side. You cancall the JavaScript method by using JavaScript Interop to get an element by ID or class.
- The getElementsByClassName() method returns a collection of all elements in the document with the specified class names.
- The getElementById() method returns a collection of all elements in the document with the specified ID names.
@page "/" @inject IJSRuntime JsRuntime <h1 id="headingElement">Hello, world!</h1> <p class="para-element">Welcome to your new app.</p> @code { protected override async void OnAfterRender(bool firstRender) { await JsRuntime.InvokeVoidAsync("elementId"); } }
<body> . . . . . . <script> function elementId() { // Get element with the specified ID name var idValue = document.getElementById("headingElement"); console.log(idValue.innerHTML); // Get element with the specified Class name var classValue = document.getElementsByClassName("para-element"); console.log(classValue[0].innerHTML); } </script> </body>