Reputation: 7
I want to remove an element when I click the button and then add it again when I click the button again.
Don't get me wrong I don't want to "hide" the element I want to remove it.
I'm not really sure why this is not working but, my guess is that this creates a reference and once I delete the original element there would be nothing to add.
Is there any way to fix this using only native javascript?
function sortClick() {
var classes = document.getElementById('btn').classList;
var myNode = document.getElementById('myNode');
var clone = myNode.cloneNode(true);
if(!classes.contains('firstClick')){
classes.add("firstClick");
myNode.parentNode.removeChild(myNode);
}
else if(classes.contains('firstClick')) {
classes.remove('firstClick');
document.body.appendChild( clone );
}
};
#btn {
cursor: pointer;
}
.firstClick {
color: red;
}
<div id='btn' onClick='sortClick()'>click</div>
<div id=myNode>removed then added</div>
Upvotes: 0
Views: 1260
Reputation: 1676
You have a problem because you don't store the element in a global variable but using a local one. Check this out. Hope it works for you.
var clone;
function sortClick() {
var classes = document.getElementById('btn').classList;
if (document.getElementById('myNode')) {
var myNode = document.getElementById('myNode');
clone = myNode.cloneNode(true);
}
if (!classes.contains('firstClick')) {
classes.add("firstClick");
myNode.parentNode.removeChild(myNode);
} else if (classes.contains('firstClick')) {
classes.remove('firstClick');
document.body.appendChild(clone);
}
};
#btn {
cursor: pointer;
}
.firstClick {
color: red;
}
<div id='btn' onClick='sortClick()'>click</div>
<div id='myNode'>removed then added</div>
Upvotes: 1
Reputation: 1648
Hey sorry about that comment earlier. I've just prepared a pen for you.
Here you can see :=)
Right about explanation;
in your code everytime you sortClick() it re-tries to cloneNode
from myNode
which in the second time it's null. That's why you had that error =)
var clone;
function sortClick() {
var classes = document.getElementById('btn').classList;
var myNode = document.getElementById('myNode');
if(!clone) {
clone = myNode.cloneNode(true);
}
if (!classes.contains('firstClick')) {
classes.add("firstClick");
myNode.parentNode.removeChild(myNode);
}
else if (classes.contains('firstClick')) {
classes.remove('firstClick');
document.body.appendChild(clone);
}
};
https://codepen.io/halilcakar/pen/WNQLqGq?editors=1111
Upvotes: 0