I'm making a project, and in some line, there's a check button that when checked it relocates it's parent to the bottom. Here's it's markup :
<div id="tasksWrapper">
<div class="subTaskWrapper">
<div class="subTask">
<div class="subMarker"></div>
<label class="subTaskLabel"></label>
<div class="subHolder"></div>
<div class="subOptions">
<ul>
<li id="subInfo">Details</li>
<li id="subEdit">Edit</li>
<li id="subDelete">Delete</li>
</ul>
</div>
<div class="checkButton"></div>
<div class="optTrigger"></div>
</div>
// more than one of that subTask divs ...
</div>
</div>
And here's it's code :
$("#tasksWrapper").on("click", ".subTask .checkButton", function(){
if($(this).parent().data("checked") == true){
$(this).css("opacity", "0.2")
.siblings(".optTrigger , .subHolder").show()
.parent().data("checked",false);
} else {
$(this).css("opacity", "1.0")
.siblings(".optTrigger , .subHolder").hide()
.parent().data("checked",true).appendTo($(this).parent().parent());
}
});
I want the .subTask
div to be appended to .subTaskWrapper
div, so in the else
case i tried this first :
else {
$(this).css("opacity", "1.0")
.siblings(".optTrigger , .subHolder").hide()
.parent().data("checked",true).appendTo($(this).parent());
}
I thought .appendTo
in this case will append .subTask
div to the .subTaskWrapper
div, but i got this error :
Uncaught Error: HIERARCHY_REQUEST_ERR: DOM Exception 3
But when i added another .parent()
to the .appendTo($(this).parent())
, it worked, so it became
.appendTo($(this).parent().parent())
I want to know why this Exception is generated in the first case and how .appendTo
is affected when it's located after .parent()
, Does it append .parent()
or just the original $(this)
?
It looks like you're appending an element to itself; that would explain the DOM hierarchy error. If you strip out the core parts of the chain, the effect is:
$(this).parent().appendTo($(this).parent());
In other words:
$(this).css("opacity", "1.0") // $(this) refers to checkButton
.siblings(".optTrigger , .subHolder") // context is still checkButton
.hide()
.parent() // context is now subTask
.data("checked",true) // still subTask
.appendTo($(this).parent()); // $(this).parent() is subTask
// so, this line says to append subTask to itself