Replacing id in JS - this only works once. What for?

I am playing around with click events and I notice that this feature only works the first time. Why is this? How can I make it so that it is possible to constantly change the id between two elements?

And would there be a significant change in approach if someone could pass id among more elements?

I don't use jQuery at all. Thank you.

 window.onload = function() {
	document.addEventListener('click', function(e) {
	  document.getElementById("purpleSquare").id = 'redSquare';
	  document.getElementById("redSquare").id ="purpleSquare";
	})
};
      

#redSquare {
	background-color: red;
    width: 20px;
    height: 20px;
}
#purpleSquare {
	background-color: purple;
    width: 20px;
    height: 20px;
}
      

        <div id="redSquare"></div>

        <div id="purpleSquare"></div>
      

Run code


+3


source to share


2 answers


Because after running this code ...

document.getElementById("purpleSquare").id = 'redSquare';

      

... there will be two elements with id="redSquare"

.

Hence it would be unreliable:

document.getElementById("redSquare")

      

In DOM2 and DOM3, the behavior was undefined:



The behavior is undefined if more than one element has this one ID

.

In DOM4, the first element will be returned. So the first time you click on it, it will work because you want to get the first one. But when you click again, you want the second one, so it doesn't work.

Instead, you can store the elements in variables before changing their IDs.

var el1 = document.getElementById("purpleSquare"),
    el2 = document.getElementById("redSquare");
el1.id = 'redSquare';
el2.id ="purpleSquare";

      

document.addEventListener('click', function(e) {
  var el1 = document.getElementById("purpleSquare"),
      el2 = document.getElementById("redSquare");
  el1.id = 'redSquare';
  el2.id ="purpleSquare";
})
      

#redSquare {
  background-color: red;
  width: 20px;
  height: 20px;
}
#purpleSquare {
  background-color: purple;
  width: 20px;
  height: 20px;
}
      

<div id="redSquare"></div>
<div id="purpleSquare"></div>
      

Run code


+5


source


Try switching between IDs like:

 document.getElementById("purpleSquare").id = 'xxxxxx';
 document.getElementById("redSquare").id ="purpleSquare";
 document.getElementById("xxxxxx").id = 'redSquare';

      

This should work. Because if you run this line of code:

document.getElementById("redSquare").id ="purpleSquare";

      



without the first:

 document.getElementById("purpleSquare").id = 'xxxxxx';

      

you will have two elements with id = "purpleSquare" . and this creates a problem if you try to run:

 document.getElementById("purpleSquare").id = 'redSquare';

      

+2


source







All Articles