Aman Ahmed
Aman Ahmed

Reputation: 9

How to change id multiple times by clicking button multiple times?

I have to change shapes by clicking on the button on web page .So for that I I made multiple id's so for every click of the button current id gets changed into another id and shape changes. every id has properties of a particular shape.

var shapeBtn = document.getElementById("cng_shape");

shapeBtn.onclick = () => {
    if (document.getElementById("shape").id == "shape") {
        document.getElementById("shape").id = "shape1";
        // document.getElementById("shape").setAttribute("id","shape1");
        //
    } else if (document.getElementById("shape1").id == "shape1") {
        document.getElementById("shape1").setAttribute("id", "shape3");
    } else if (document.getElementById("shape3").id == "shape3") {
        document.getElementById("shape3").setAttribute("id", "shape");
    }
};

I tried using if statements and check whether the current id is true and it its true change its id to new one.

Upvotes: 0

Views: 51

Answers (1)

MAYUR SANCHETI
MAYUR SANCHETI

Reputation: 152

try below code , also need to check if id is exist like below,

var shapeBtn = document.getElementById("cng_shape");

shapeBtn.onclick = () => {
     
    if ( document.getElementById("shape") && document.getElementById("shape").id == "shape") {
        document.getElementById("shape").id = "shape1";
        // document.getElementById("shape").setAttribute("id","shape1");
        //
    } else if ( document.getElementById("shape1") && document.getElementById("shape1").id == "shape1") {
        document.getElementById("shape1").setAttribute("id", "shape3");
    } else if ( document.getElementById("shape3") &&  document.getElementById("shape3").id == "shape3") {
        document.getElementById("shape3").setAttribute("id", "shape");
    }
};
<div id="shape">test</div>
<input type="button" id="cng_shape" value="click" />

Upvotes: 3

Related Questions