Here is a clean and efficient JavaScript function that loops over all <li> nodes in the document, checks their data-mtime attribute, and removes those whose value equals "30. Mai 07:02". The function uses modern DOM manipulation techniques to ensure clarity and maintainability.
Implementation
function removeLiByDataMtime(targetMtime) {
// Select all <li> elements in the document
const liElements = document.querySelectorAll('li[data-mtime]');
// Loop through each <li> element
liElements.forEach(li => {
// Check if the data-mtime attribute matches the target value
if (li.getAttribute('data-mtime') === targetMtime) {
// Remove the <li> element from its parent
li.remove();
}
});
}
// Usage example:
removeLiByDataMtime("30. Mai 07:02");
Explanation of the Code
-
Selecting <li> Elements:
- The
document.querySelectorAll('li[data-mtime]') method selects all <li> elements that have a data-mtime attribute. This ensures we only process relevant nodes.
-
Iterating Over the NodeList:
- The
forEach method is used to iterate over the NodeList returned by querySelectorAll. This approach is concise and avoids manual index management.
-
Checking the data-mtime Attribute:
- For each
<li> element, the getAttribute('data-mtime') method retrieves the value of the data-mtime attribute. This value is then compared to the target string ("30. Mai 07:02").
-
Removing Matching Nodes:
- If the
data-mtime value matches the target, the remove() method is called on the <li> element. This method removes the node from its parent in the DOM.
-
Function Parameterization:
- The function accepts a
targetMtime parameter, making it reusable for different target values.
Sample HTML Before Execution
<ul>
<li data-mtime="29. Mai 06:45"><a href="/web/filelists/__tmp__device_and_dashboard.txt">__tmp__device_and_dashboard.txt</a></li>
<li data-mtime="26. Mai 11:00"><a href="/web/filelists/_tmp_filelist">_tmp_filelist</a></li>
<li data-mtime="30. Mai 07:02"><a href="/web/Work_in_Progress/ccch_Development/abrechnung.html">abrechnung.html</a></li>
</ul>
Result After Execution
After calling removeLiByDataMtime("30. Mai 07:02"), the resulting HTML will be:
<ul>
<li data-mtime="29. Mai 06:45"><a href="/web/filelists/__tmp__device_and_dashboard.txt">__tmp__device_and_dashboard.txt</a></li>
<li data-mtime="26. Mai 11:00"><a href="/web/filelists/_tmp_filelist">_tmp_filelist</a></li>
</ul>
Key Notes
- Efficiency: The function directly targets
<li> elements with a data-mtime attribute, avoiding unnecessary processing of unrelated nodes.
- Reusability: By parameterizing the target value, the function can be reused for different
data-mtime values without modification.
- Modern DOM Methods: The use of
querySelectorAll and forEach ensures compatibility with modern browsers while maintaining readability.
This implementation is robust and adheres to best practices for DOM manipulation in JavaScript.