So I have a html node for some tasks that user can create, when user clicks sort by date I want it to be sorted and changed in the html and other way round but I don’t know how to do the html part, any ideas?
I can do the sorting in JS its really nothing hard but I just don’t know how to apply the sort to html, maybe to store nodes into JavaScript variables and than clear the list of tasks and append child with sorted way?
2
Answers
Create an HTML file with a .html extension (e.g., index.html).
Open the HTML file in a text editor or an integrated development environment (IDE).
Within the section of the HTML file, add a tag to include your JavaScript code. You can either write the JavaScript code directly within the tag or reference an external JavaScript file using the src attribute.
Your input nodes need to be dynamic.
Ideally, you would use a framework like react which makes doing stuff like that really easy.
If you’re using vanilla javascript then the easiest way (as you already suggested) would be to
parent.innerHTML = ''
(there are better ways to clear the child nodes of parents, this is not a recommended way due to it not clearing any event listeners the child has)parent.append(child)
functionAs an example
Consider the html to be
and the associated js to be
Here the
renderList
function loads the content in the HTML dynamically based on your listItems by deleting any child node the parent might have and then appending new child nodes, which is first done duringonload
.When you click the button to sort, it sorts the listItems array based on the
order
property, and then runsrenderList
again.A working js fiddle can be found here https://jsfiddle.net/1Lwqtu8e/20/