With the Move_ULLI function, how is it possible to move the entire List (UL LI) into the DIV with the destination class?
I'm not intending to use IDs to identify DIVs or UL List, just by ClassName() and TagName().
HTML:
<div >
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<div ></div>
<input type="button" onclick="Move_ULLI" value="MOVE ULLI" />
</div>
JavaScript:
<script>
function Move_ULLI() {
var fragment = document.createDocumentFragment();
fragment.appendChild(document.querySelectorAll("ul"));
document.getElementsByClassName('destination').appendChild(fragment);
}
</script>
Intended Result:
<div >
<div >
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
</div>
<input type="button" onclick="Move_ULLI" value="MOVE ULLI" />
</div>
CodePudding user response:
A few issues:
- You never call the function. The
onclickattribute lacks the parentheses after the function to actually invoke it. getElementsByClassNamereturns a node list and has noappendChildmethod. UsequerySelectorinstead (with the right selector)querySelectorAllreturns a node list, while you want to just get a node, so usequerySelectorthere as well- There is no need to create a fragment. Just append the
ulnode and it will move.
function Move_ULLI() {
document.querySelector('.destination')
.appendChild(document.querySelector("ul"));
}
.destination { background-color: yellow }
<div >
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<div ></div>
<input type="button" onclick="Move_ULLI()" value="MOVE ULLI" />
</div>
CodePudding user response:
There are multiple things wrong with your example:
You need to add the parenthesis to the end of your function name in your inline
onclickmarkup for your Html (I would suggest moving to using event listeners, but for the sake of giving you a working example I am leaving it).If you use
querySelectorAllorgetElementsByClassNameyou get back a node list, so you either have to index the node list or usequerySelectorand/orgetElememtById
Here's a working solution:
function Move_ULLI() {
var fragment = document.createDocumentFragment();
fragment.appendChild(document.querySelector("ul"));
document.getElementsByClassName('destination')[0].appendChild(fragment);
}
.destination {
background-color:green;
}
<div >
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<div ></div>
<button type="button" onclick="Move_ULLI();">
MOVE ULLI
</button>
</div>
Solution using event handler
function Move_ULLI() {
var fragment = document.createDocumentFragment();
fragment.appendChild(document.querySelector("ul"));
document.getElementsByClassName('destination')[0].appendChild(fragment);
}
window.addEventListener("DOMContentLoaded", () => {
document.querySelector("button").addEventListener("click", Move_ULLI);
});
.destination {
background-color:green;
}
<div >
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<div ></div>
<button type="button" onclick="Move_ULLI();">
MOVE ULLI
</button>
</div>
