<div id = 'ONE' onclick = "change to id TWO" >One</div>
What I want is that every time I click that div
it'll toggle between ID ONE and ID TWO, if it's on ID TWO and I click it, it switches to ID ONE and vice versa. How can I do that?
This is most easily accomplished with jQuery.
First thing that comes to my mind is setting a click counter to 0. If it's even, we will change the id to red
, if it's odd, we change the id to blue
.
var clickCount = 0; $("div").on("click", function() { clickCount++; $("div").attr("id", clickCount % 2 === 0 ? "blue" : "red"); });
#red { color: red; } #blue { color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>This is a div</div>
Here is the native JavaScript equivalent.
var div = document.getElementById("my-div"); var clickCount = 0; div.addEventListener("click", function() { clickCount++; div.setAttribute("id", clickCount % 2 === 0 ? "blue" : "red"); });
#red { color: red; } #blue { color: blue; }
<div id="my-div">This is a div</div>
I found the solution:
function changediv() {
if (document.getElementById("one")) {
document.getElementById("one").id = "two";
} else {
document.getElementById("two").id = "one";
}
}
Then on your div
<div id = "one" onclick = "changediv()" >Your stuff</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.