-1

I want to change the innerHTML so for every circle thats the same it adds +1

if (document.getElementById("circle1").style.backgroundColor == document.getElementById("circle5").style.backgroundColor) {
    document.getElementById("point2").innerHTML = +1
}

if (document.getElementById("circle2").style.backgroundColor == document.getElementById("circle6").style.backgroundColor) {
    document.getElementById("point2").innerHTML = +1
}
MH2K9
  • 11,951
  • 7
  • 32
  • 49
Dario
  • 35
  • 3

2 Answers2

0

I suggest you to use innerText then. First get the old value and cast to Number then add by 1 and replace the old value. Example:

if (document.getElementById("circle1").style.backgroundColor == document.getElementById("circle5").style.backgroundColor) {
    let obj = document.getElementById("point2");
    let oldValue = Number(obj.innerText);
    obj.innerText = oldValue + 1;
}

if (document.getElementById("circle2").style.backgroundColor == document.getElementById("circle6").style.backgroundColor) {
    let obj = document.getElementById("point2");
    let oldValue = Number(obj.innerText);
    obj.innerText = oldValue + 1;
}

See difference between innerText and innerHtml.

MH2K9
  • 11,951
  • 7
  • 32
  • 49
0

document.getElementById("point2").innerHTML doesn't give you a number, so you cannot add 1 to it. first you need to parse the content to a number (like with parseInt or Number), and then you can add 1.

// creating the reference variable (for smaller code)
var point2 = document.getElementById("point2").innerHTML

if (document.getElementById("circle1").style.backgroundColor ==
  document.getElementById("circle5").style.backgroundColor) {
  document.getElementById("point2").innerHTML = increment(point2)
}
if (document.getElementById("circle2").style.backgroundColor ==
  document.getElementById("circle6").style.backgroundColor) {
  document.getElementById("point2").innerHTML = increment(point2)
}

// function to increment the value of point2
function increment(html) {
  return Number(document.getElementById("point2").innerHTML) + 1
}
#circle1 {
  background-color: red;
}

#circle5 {
  background-color: red;
}

#circle2 {
  background-color: red;
}

#circle6 {
  background-color: red;
}
<div id="circle1">C1</div>
<div id="circle5">C5</div>
<br />
<div id="circle2">C2</div>
<div id="circle6">C6</div>

<div id="point2">0</div>
muka.gergely
  • 8,063
  • 2
  • 17
  • 34