I'm having some troubles to find what is wrong in my code to remove all the child of my list:
document.getElementById('btnGetExistingFiles').onclick = function(){
var ul = document.getElementById('listExisting');
//we split the files in a array
var existingFiles = "a.yml b.yml c.yml d.yml".split(" ");
//if the list already contains some values we remove them
if(ul.hasChildNodes()){
ul.empty();
}
//for each file we add an element in the list
existingFiles.forEach(function(fileName) {
console.log("add files");
var li = document.createElement("li");
var a = document.createElement("a");
a.setAttribute("href", "#");
a.setAttribute("class", "oneExistingFile");
a.appendChild(document.createTextNode(fileName))
li.appendChild(a);
ul.appendChild(li);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<button id="btnGetExistingFiles" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu" id="listExisting">
</ul>
</div>
and I don't know why my element has child despite it's an empty one at the beginning but anyway even if I do ul.empty()
in the browser terminal when the list is full I have the error
While .empty() is a jquery function .. I think you need to use ul.innerHTML = '';
instead of ul.empty()
document.getElementById('btnGetExistingFiles').onclick = function(){
var ul = document.getElementById('listExisting');
//we split the files in a array
var existingFiles = "a.yml b.yml c.yml d.yml".split(" ");
//if the list already contains some values we remove them
if(ul.hasChildNodes()){
ul.innerHTML = '';
}
//for each file we add an element in the list
existingFiles.forEach(function(fileName) {
console.log("add files");
var li = document.createElement("li");
var a = document.createElement("a");
a.setAttribute("href", "#");
a.setAttribute("class", "oneExistingFile");
a.appendChild(document.createTextNode(fileName))
li.appendChild(a);
ul.appendChild(li);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<button id="btnGetExistingFiles" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu" id="listExisting">
</ul>
</div>
Theres no Element.prototype.empty property. But theres one in jquery:
$(ul).empty();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With