0

I want to add brackets to a players score, but when updating on an interval it's also appending both string brackets multiple times instead of once.

setInterval(() => {
    for(let i in topmass){
       topmass[i].innerText = "[" + topmass[i].textContent + "]"
    } 
}, 100)

Name: [score] not: Name: [[[[[[score]]]]]]

  • 1
    can you provide more details , what's the purpose of writing the code inside for loop and inside setInterval ? – 27mdmo7sn Jul 15 '19 at 05:00
  • to update the score, but i don't want want there to be multiple brackets per score. – Tima Donbragoni Jul 15 '19 at 05:03
  • Why use an interval if topmass[i].textContent does not change? Also don't use for..in for an array. Can you post more code so we can figure out why you would use an interval? – mplungjan Jul 15 '19 at 05:13
  • Lastly: https://stackoverflow.com/questions/13651022/square-brackets-with-css – mplungjan Jul 15 '19 at 05:14
  • Using the DOM to store state leads to some pretty hard to maintain code. I think you should look at storing what ever is in topmass[i].textContent in a data structure. – BlueWater86 Jul 15 '19 at 05:16

2 Answers2

1

each time you do this you add [] to

 topmass[i].innerText = "[" + topmass[i].textContent + "]"

you change to [dont forget to check null]

 topmass[i].innerText = "[" + topmass[i].textContent.match('[0-9,a-z]+')[0] + "]"
kunal verma
  • 456
  • 5
  • 13
  • I think this is an X/Y problem. It would be great to know why he even adds brackets in an interval – mplungjan Jul 15 '19 at 05:15
  • @mplungjan Alternative if you have less elements in tompass like less than 10 thenyou could do somethimng like [
    SCORE
    ] you may not need to do anything with [] ...but if you are constrained with html OR if you have >10 elements and dont want a messy dom then first one is ok
    – kunal verma Jul 15 '19 at 05:26
  • that's way easier, thanks for that snipet! @mplungjan – Tima Donbragoni Jul 15 '19 at 05:42
-1

Well, maybe this will help.

Instead of extracting the score always from textContent, you can maintain another member inside each topmass element(say score). After every interval, you can update the score and innerText accordingly.

setInterval(() => {
    // Update or initialize score, e.g. topmass[i].score += 10
    for(let i in topmass){
       topmass[i].innerText = "[" + topmass[i].score + "]"
    } 
}, 100)
Crash0v3rrid3
  • 518
  • 2
  • 6
  • You shouldn't be using [custom attributes](https://stackoverflow.com/questions/992115/custom-attributes-yea-or-nay) – BlueWater86 Jul 15 '19 at 05:57
  • That is completely different. And I don't disagree with that. But here we're making use of Javascript's power as a programming language, not defying HTML 5's standard. What we're doing has no relation with HTML tags, but with javascript objects. – Crash0v3rrid3 Jul 15 '19 at 10:35
  • `Tompass[i]` is a node in the DOM. You are adding a score custom attribute to each of the nodes. – BlueWater86 Jul 15 '19 at 20:54