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
onclick
attribute lacks the parentheses after the function to actually invoke it. getElementsByClassName
returns a node list and has noappendChild
method. UsequerySelector
instead (with the right selector)querySelectorAll
returns a node list, while you want to just get a node, so usequerySelector
there as well- There is no need to create a fragment. Just append the
ul
node 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
onclick
markup 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
querySelectorAll
orgetElementsByClassName
you get back a node list, so you either have to index the node list or usequerySelector
and/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>