Blazor, get Input value from Javascript created DOM Element

Viewed 2026

I have been working with Blazor quite a bit (https://blazorboilerplate.com) but I have a bit of a issue that has stumped me tonight with adding some custom D3 code to my blazor pages. The D3 / Javascript code creates several DOM input elements and I wish to retrieve the values of these created elements so I can save a DTO to my database with those values. How can I do this and what is the most efficient way? Should I just create a JSInterop method to return the input values?

domInput.attr("@ref", function (d3) {return d3.key});

I tried creating "@ref" attributes so I could use the ElementReference but D3 errors when I try to append an attribute that begins with '@'

1 Answers

After some more research from Mr. Magoo's comment you cannot interact with DOM that was / is created by JS and / or modified by JS. To get around this though you can create a JS function to return your data. So I created a helper method that returns a JSON string of my data. Then I call that JS from my Blazor code and use Newtonsoft to Deserialize it. The d3 code could easily be changed to vanilla javascript or JQuery to get the DOM elements value / innerHTML.

Blazor Code

   var data = await JsRuntime.InvokeAsync<string>("JsInteropFunc", null);

   dataDto = Newtonsoft.Json.JsonConvert.DeserializeObject<DataObjectDto> 
    (data);

Javascript Code, this case uses d3 to get the DOM Element with a class name to get the text form the DOM element:

  window.JsInteropFunc = function() {
    function cleanStr(data){
      return data.replace("$","").replace(",","").replace("%","");
    }

    return '{ totalSales: "' + cleanStr(d3.select(".totalSales").text()) + '"' +
            ', annualSales: "' + cleanStr(d3.select(".annualSales").text()) + '"' +
            ', profitMargin: "' + cleanStr(d3.select(".profitMargin").text()) + '"' +
            '}' ;    
  },
Related