javascript - swapping id's in JS - this only works one time. Why? -


i'm playing around click events, , notice function works first time. why that? how can make possible continuously swap id's between 2 elements?

and, there dramatic change in approach if 1 pass id's along among larger number of elements?

i'm not using jquery @ all. thanks.

 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>

because after running code...

document.getelementbyid("purplesquare").id = 'redsquare'; 

...there 2 elements id="redsquare".

therefore, unreliable:

document.getelementbyid("redsquare") 

in dom2 , dom3 behavior undefined:

behavior not defined if more 1 element has id.

in dom4 first element returned. therefore, first time click work because want first one. when click again, want second one, doesn't work.

instead, can store elements in variables before changing 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>


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -