Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace specific content in line in html with JS

I've got a html file and JS file

So I've got a syntax of svg in my html file :

<body>
    <svg width="500" height="100">
        <circle id="circle1" cx="20" cy="20" r="10"
        style="stroke: none; fill: #ff0000;"/>  
        <text x="47.872" y="11.064">{home/sensors/temp/kitchen} °C</text>
        <circle id="circle1" cx="20" cy="20" r="10"
        style="stroke: none; fill: #ff0000;"/>
        <title x="47.872" y="11.064" >{home/sensors/temp/bathroom} °C</title>
        <circle id="circle1" cx="20" cy="20" r="10"
        style="stroke: none; fill: #ff0000;"/>
        <text x="47.872" y="11.064">{home/sensors/temp/room} °C</text>
    </svg>
    <script type="text/javascript" src="../scripts/link.js"></script>
</body>
</html>

Currently, I've got only this in my link.js:

let listTickets = new Map([
                          ['0', '{home/sensors/temp/kitchen}'],
                          ['1', '{home/sensors/temp/bathroom}'],
                          ['2',  '{home/sensors/temp/room}']
]);

let listNumber = new Map([
                          ['0', '24'],
                          ['1', '22'],
                          ['2', '25']
]);

// var topicMatch = line.match(/\{[\w\/]+\}/g); // think need to use regex

So What I want in my js file, it's when we've got a syntax in html file like:

"{ + content + }

Need to replace (in my navigator and not in file) the same syntax by his value, for example, we are reading the html file :

detect first content : {home/sensors/temp/kitchen} => need to change by '24'
detect second content : {home/sensors/temp/bathroom} => need to change by '22'
detect first content : {home/sensors/temp/kitchen} => need to change by '25'

Thanks for your help

like image 590
oxem Avatar asked May 25 '26 14:05

oxem


2 Answers

You can use this JS code:

var all = document.getElementsByTagName("*");
for (var i = 0, max = all.length; i < max; i++) {
  for (let [key, value] of listTickets) {
    if (all[i].innerHTML.includes(value)) {
      all[i].innerHTML=all[i].innerHTML.replaceAll(value, listNumber.get(key));
    }
  }
}

It finds any match of given strings in the listTickets map in your html, and changes them with the value of listNumber map for string's key.

like image 117
Pooya Mahdavi Avatar answered May 27 '26 03:05

Pooya Mahdavi


You get more flexibility with a modern Web Component (supported in all modern Browsers)

And process your source SVG as a Template Literal String to replace values (or execute functions like: color does)

<temperature-dashboard cold="blue" warm="red">
  <template inside template so SVG is not displayed on load>
    <svg id="temperature" width="100" height="120">
      <style>
        #temperature { background:pink}
        #temperature circle { stroke:none; r:${size}}
      </style>
      <circle cx="20" cy="20"  ${color(kitchen)} ></circle>
      <text x="40" y="25">${kitchen} °C</text>
      <circle cx="20" cy="60"  ${color(bathroom)} ></circle>
      <text x="40" y="65">${bathroom} °C</text>
      <circle cx="20" cy="100" ${color(room)} ></circle>
      <text x="40" y="105">${room} °C</text>
    </svg>
  </template>
</temperature-dashboard>
<script>
  customElements.define("temperature-dashboard", class extends HTMLElement {
    connectedCallback() {
      setTimeout(() => { // wait till innerHTML is fully parsed
        this.svgsource = this.querySelector("template").innerHTML;
        let data = { bathroom: 23, kitchen: 24, room: 19 };
        this.setdata( data );
      })
    }
    setdata( dataIn ){
      let fulldata = { 
            size: 15,
            color : (degrees) => {
              let coldColor = this.getAttribute("cold");
              let warmColor = this.getAttribute("warm");
              return `fill="${degrees < 20 ? coldColor : warmColor }"`
            },
            ...dataIn
      }
      const parseTemplateLiteral = (str, data = {}) => {
        let params = Object.keys(data).join(",");
        return new Function("p", // Function savely parsing Template Literal
               "return((" + params + ")=>`" + str + "`)(...Object.values(p))")(data);
      }
      this.innerHTML = parseTemplateLiteral(this.svgsource, fulldata);
    }
  });
</script>
like image 41
Danny '365CSI' Engelman Avatar answered May 27 '26 02:05

Danny '365CSI' Engelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!