I want to add or remove required
attr when the li
number changes in a ul
.
If there are no li
s the required
attr will be added, and if there are li
s the required
attr will be will be removed.
The function works great but only for the first input[type="file"]
I want the function to wort for all the file inputs in the page.
I want it to observe changes in every one of the.
I thought doing
const fileList = document.querySelectorAll('ul.file-list')[x];
observer.observe(fileList, {
childList: true
})
but I have two problems:
- how do I find the array location of the
ul.file-list
I am working at (instead of thex
). - I prefer not to use an event Listener.
Any help would be great.
const observer = new MutationObserver(function(mutations){
mutations.forEach(function(mutation){
let liLength = mutation.target.getElementsByTagName("li").length;
if(mutation.addedNodes.length){
console.log('added',mutation);
if(liLength != 0){
mutation.target.parentElement.getElementsByTagName('input')[0].required = false;
}
}
if(mutation.removedNodes.length){
if(liLength == 0){
mutation.target.parentElement.getElementsByTagName('input')[0].required = true;
}
}
});
});
const fileList = document.querySelector('ul.file-list');
observer.observe(fileList, {
childList: true
})
This the html markup. This is one of the 27 'ul's in the page I have
<div class="custom-file" id="tz-file">
<label class="custom-file-label" for="tzfile">add file</label>
<ul class="file-list">
<li><a href="./uploads/9999999/1.pdf" target="_blank"> 1.pdf </a>
<span class="item-file" id="2018-9999999-21314-1">remove file</span></li>
</ul>
<input type="file" class="custom-file-input" id="tzfile" name="tzfile">
</div>