1

I am creating a chrome app and I need to change the id of a circle (it is tied to some CSS, so the id determines the color) to make the circle a different color. I also need to change the value of the button to "Lock". Note that this is a chrome app. Here is my JavaScript:

document.getElementById("clickme").addEventListener('click', function() {
      document.getElementById('clickme').id = 'clicked';
    }

    if (document.getElementById('clickme').id = "clicked") {
      document.getElementById('redcircle').id = 'greencircle';
      document.getElementById('clicked').value = 'Lock';
    }

And my HTML:

<tr>
<td>Door 116</td>
<td><span><div class="circle" id="redcircle"></div></span></td>
<td><button type="button" id="clickme" value="unlock">Unlock</button></td>
Barmar
  • 741,623
  • 53
  • 500
  • 612
Ahoop
  • 35
  • 10
  • `if (document.getElementById('clickme').id="clicked")` How can this ever be true? If the ID is `clickme` then it's not `clicked`. – Barmar Mar 17 '19 at 12:24
  • 1
    1) `if (document.getElementById('clickme').id="clicked")` is an assignment, not comparison - please use `===`, 2) when fixed, this comparison will never be true because it's like comparing 'a' and 'b', 3) The correct approach is to use a class name, not to change an id. 4) Store the element reference in a variable – wOxxOm Mar 17 '19 at 12:24
  • 4
    You should use classes instead of the ID for this purpose – Steve T Mar 17 '19 at 12:25
  • Possible duplicate of (https://stackoverflow.com/questions/1650299/how-do-i-change-the-id-of-a-html-element-with-javascript) – Davide Vitali Mar 17 '19 at 12:25

1 Answers1

0

Your javascript is quite completely wrong :

  • You should use Class instead of id for changing the color.
  • It's a bad idea to change id of an element.

Your code you should look like this:

    document.getElementById("clickme").addEventListener('click', function() {
        let circle = document.getElementsByClassName('circle');
        if (circle.style.color == "red") {
          circle.style.color = "green";
          document.getElementById('click').value = 'Lock';
        }
        else {
          circle.style.color = "red";
          document.getElementById('click').value = 'Unlock';
        }
});

Do not hesitate if you have more question!

You should take a look at:

https://www.w3schools.com/js/js_comparisons.asp

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style