If that is your whole code, I guess it adds the <div1> and then nothing else happens? If you want to create a switch, you’d need a button (or any other element), add an event listener, and then run the code again when the button is clicked.
I see, the problem is that every time the function is called, the boolean is re-initialised to true. You have two options:
Keep track of the boolean by adding a value attribute to the button, toggle it between true and false on each click, and use that button’s value in your function. You’d have to pass the the event parameter to the handler and access the value through event.target.value (note that it is of type String)
<button id="CreateNew" value="true" onclick="create(event)">Create Product</button>
function create(event){
// get the string value and convert to an actual boolean
var bool = event.target.value === 'true' ? true : false;
// get the button and set its new value
var button = document.getElementById('CreateNew');
button.value = !bool;
// rest stays the same
}
The more elegant but more advanced way is to use a closure. I have never written code in C#, so I can’t say if it’s a familiar concept for you, but this is how the code would look like:
<button onclick="closure()">Create Product</button>
function create(){
// these variables will be evaluated once during the assignment of var closure,
// and their values will be remembered
var bool = true;
var getid = document.getElementById("A");
var div1 = document.createElement("div");
div1.setAttribute("id", "newid");
// this function will run on every button click, and still has access
// to the latest value of the boolean
return function(){
if (bool) {
getid.appendChild(div1)
} else {
document.getElementById("newid").remove();
}
bool = !bool;
}
}
var closure = create();
I found it to be a difficult concept to grasp, but if you have some programming experience and know about variable scopes, you’ll get your head around it eventually.
One more comment - in JavaScript, don’t use var (it’s outdated), use const instead for all your variables, except the boolean. You want to reassign it on every click, so it should be declared with let.