JSFiddle - React, Tailwind, and code Playground
by steve
HTML
<div id='container'>
Container
<a>
Anchor
<div id='movingDiv' class='mover'>Child of Anchor</div>
</a>
</div>
<!-- Controls -->
<p>
<button type='button' onclick='childSiblingToggle()'>Child - Sibling toggle</button>
</p>
<p>
<button type='button' onclick='removeAnchor()'>Remove Anchor</button>
</p>
CSS
/* This CSS is for presentation only, it has no effect on the script. */
#container {
background:cornflowerblue;
font-size:14px;
font-family:arial,verdana;
padding:10px;
}
#container>a {
background:khaki;
display:block;
margin:2px;
padding:10px;
}
#container>a>.mover {
background:salmon
}
#container>.mover {
background:lightgreen;
}
p {
margin:10px
}
.mover {
margin:2px;
padding:5px;
}
JavaScript
//========== Toggle #movingDiv as child or sibling.
childSiblingToggle = function() {
// Get collection of <div> elements inside container
var div = $('container').getElementsByTagName("div");
// Check if there are any elements returned, if so, take the first one.
if(div.length>0) { div = div[0]; }
// If not, alert and quit this function.
else { alert("<div> has been removed."); return; }
// parentNode of div IS an anchor? Append to parent.
if(div.parentNode.nodeName=="A") {
$('container').appendChild(div);
div.innerHTML = "Child Of Container"
}
// Parent ISN'T an anchor?
else {
// Check to see if anchor exists, if not, quit this function.
if($('container').getElementsByTagName("a").length==0) {
alert("<a> has been removed.");
return false;
}
// Otherwise, append to anchor.
$('container').getElementsByTagName("a")[0].appendChild(div);
div.innerHTML = "Child Of Anchor"
}
}
//========== Removes first <a> tag in container.
removeAnchor= function() {
$('container').removeChild($('container').getElementsByTagName("a")[0]);
}