Jeremy
Jeremy

Reputation: 25

Replace content in different line 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>

Need to replace the same syntax by his value, for example :

detect 1 : {home/sensors/temp/kitchen} => change by '35'
detect 2 : {home/sensors/temp/bathroom} =>  change by '30'
detect 3 : {home/sensors/temp/kitchen} =>  change by '21'

What I'm doing :

let listNumber = new Map([
    ['{garage/temp}', '35'],
    ['{home/sensors/temp/kitchen}', '30'],
    ['{home/sensors/temp/bathroom}', '21'],
]);

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

I've got undefined and don't understand why I've got this

Thanks for your help

Upvotes: 0

Views: 51

Answers (1)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

I'm not sure about the accuracy of your svg, but I would recommend first of all to not iterate over all elements but just the text elements within the svg (querySelectorAll).

const replacers = [
  ["{home/sensors/temp/kitchen}", "35"],
  ["{home/sensors/temp/bathroom}", "30"],
  ["{home/sensors/temp/room}", "21"],
]

Array.from(document.querySelectorAll("svg > text")).forEach((element) => {
  replacers.forEach((replacer) => {
    element.textContent = element.textContent.replace(replacer[0], replacer[1]);
  })
});
<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>

Upvotes: 1

Related Questions