Home > Back-end >  How to delete specific element nodes based on e.g. an empty attribute value of the provided markup?
How to delete specific element nodes based on e.g. an empty attribute value of the provided markup?

Time:11-10

How does one delete element nodes in case the provided markup comes for example with empty attribute values like in the example below?

E.g. any image element with a missing src attribute needs to be deleted.

let elements = document.getElementsByTagName('img');
elements.forEach(function(element) {
  console.log(element);
  let src = element.src
  if (!ValidURL(src))
    element.parentNode.removeChild(element);
});

function ValidURL(str) {
  var pattern = new RegExp('^(https?:\/\/)?'   // protocol
    '((([a-z\d]([a-z\d-]*[a-z\d])*)\.) [a-z]{2,}|'   // domain name
    '((\d{1,3}\.){3}\d{1,3}))'   // OR ip (v4) address
    '(\:\d )?(\/[-a-z\d%_.~ ]*)*'   // port and path
    '(\?[;&a-z\d%_.~ =-]*)?'   // query string
    '(\#[-a-z\d_]*)?$', 'i'); // fragment locater
  if (!pattern.test(str)) {
    alert("Please enter a valid src.");
    return false;
  } else {
    return true;
  }
}
<img id="image-1206-140" alt="" src=""  href="site.com">
<img id="image-1207-140" alt="" src=""  href="">
<img id="image-1207-140" alt="" src=""  href="">

CodePudding user response:

"How to delete [...] if [a certain] html attribute is empty"

Start with the correct query method (e.g. querySelectorAll) and the correct selector. Then remove each queried element node ... document.querySelectorAll('img[src=""]').forEach(elm => elm.remove());

document
  .querySelectorAll('img[src=""]')
  .forEach(node => node.remove());
li:empty {
  min-height: 1.4em;
}
li:empty::after {
  content: "    missing image    ";
}
<ul>
  <li><img src="https://picsum.photos/80/60?grayscale"/></li>
  <li><img src=""/></li>
  <li><img src="https://picsum.photos/60/60?grayscale"/></li>
  <li><img src=""/></li>
  <li><img src="https://picsum.photos/81/61?grayscale"/></li>
  <li><img src=""/></li>
</ul>

  • Related