HTML panel, change element by id

I’m using the ‘HTML panel’ plugin by aidanmountford, which contains a panel that allows you to enter some JS (and CSS and HTML). Its been a few months since I’ve done any work in Javascript, and I can’t seem to figure out how to change an element by ID in this panel.

My simplified and functioning HTML is:

    <svg id='svg_container' width='100%' height='4rem'>

     <g class="bars">
       <rect id='thermom_cont' class='thermom'fill='#999' width='100%' height='10'y="7"></rect>
       <rect id='procA_ID' class='thermom' fill='#1ca4c2' width='10%' height='10' y="7"></rect>

        <text id='dateLabel' fill='#BBB' x='94%' y='50'>Date Label</text>

In this HTML I have two overlapping bars (on the same y axis), one long grey and the other short and blueish(#1ca4c2), and a date label in the bottom corner. The JS that I am trying is unable to find the element by ID.

I have tried addressing one of the id’s directly using:

this.$.dateLabel.innerHTML = "Hello World";
// or 
$.dateLabel.innerHTML = "Hello World";

for both of those the console spits out: “TypeError: Cannot read property ‘dateLabel’ of undefined”

I’m not sure how to interpret the instructions which say:

htmlnode passes the HTMLElement of the html content on the panel. THis allows direct access to and editing of the html content:

htmlnode.innerHTML = “Hello World”;

I tried:

htmlnode.dateLabel.innerHTML = "Hello World"

and I got the same type error.

The last little bit of instructions included in this panel are:

JavaScript Code: onInit(ctrl, htmlnode)

  • This code is executed once , right after the first initialization of the SVG
  • @param {MetricsPanelCtrl} ctrl Instance of current grafana panel object.
  • @param {HTMLElement} htmlnode Html DOM node containing html data.

I’m not 100% sure how to interpret this, I’ve tried substituting in the ID name for ‘HTMLElement’ or ‘htmlnode’ with no luck.

I have only had success generating an html string (called ‘html’) and executing:

 htmlnode.innerHTML = html

But I would really like to address an element by ID or Class, if possible. Am I misinterpreting this app, is it possible to use ID or Class to change an element?

I think I found the answer. Sorry if it is basic but since I found others with the same question, here is my solution:

htmlnode.getElementById("dateLabel").innerHTML = "New text!";

so to alter my blue bar, this works too:

htmlnode.getElementById("procA_ID").setAttribute('width', '' + 100 + '%');
1 Like