Home > database >  javascript to check if file extension is found in list
javascript to check if file extension is found in list

Time:12-01

I am using javascript to check if a pdf or doc extension is found in the item of a list. If it is, I want to remove that element. Is there an easy way to make this work. I can detect if its there. It returns true, but not sure how to select that specific element.

if (document.querySelector("#myList").innerHTML.includes(".pdf") || (".doc")) {
  //find and remove item

}
<div id="myList">
<div >
  <img  src="/v2l/le/1196xx/discussions/posts/26adsd89/ViewAttachment?fileId=273383625">
  <div >photoTest.jpg</div>
</div>
<div >
  <img  src="/v2l/le/11961xx/discussions/posts/26ss489/ViewAttachment?fileId=27773626">
  <div >dog.png</div>
</div>
<div >
  <img  src="/v2l/common/viewFile.v2lfile/Im/638054389092471030/testpde.pdf?ou=11961xxx&amp;fid=ZTZlMDllZGEtMWM0Yi00ZWRlLWI5ODAtMjhhNWRmYjc1MzBmO0dyYXBoaWNEZXNpZ25fT25saW5lX0NvdXJzZU91dGxpbmUucGRmOzU1ODY0MDE">
  <div >testpde.pdf</div>
</div>
</div>

CodePudding user response:

In order to remove the elements if a child contains a specific string (.pdf or .doc) use:

// DOM utility functions:

const el = (sel, par) => (par || document).querySelector(sel);
const els = (sel, par) => (par || document).querySelectorAll(sel);

// Utility functions:

const isDocument = (fileName) => /\.(pdf|doc)$/.test(fileName);

// Task: Remove element if child text is document

els(".style").forEach(elStyle => {
  const elFile = el("div", elStyle);
  const text = elFile.textContent.trim();
  isDocument(text) && elFile.remove();
});
<div id="myList">
  <div >
    <img  src="/v2l/le/1196xx/discussions/posts/26adsd89/ViewAttachment?fileId=273383625">
    <div >photoTest.jpg</div>
  </div>
  <div >
    <img  src="/v2l/le/11961xx/discussions/posts/26ss489/ViewAttachment?fileId=27773626">
    <div >dog.png</div>
  </div>
  <div >
    <img  src="/v2l/common/viewFile.v2lfile/Im/638054389092471030/testpde.pdf?ou=11961xxx&amp;fid=ZTZlMDllZGEtMWM0Yi00ZWRlLWI5ODAtMjhhNWRmYjc1MzBmO0dyYXBoaWNEZXNpZ25fT25saW5lX0NvdXJzZU91dGxpbmUucGRmOzU1ODY0MDE">
    <div >testpde.pdf</div>
  </div>
</div>

Additional resource:

CodePudding user response:

function hasExtOfList(src, list) {
   return list.some(ext => src.includes(ext))
}

hasExtOfList(
  document.querySelector("#myList").innerHTML,
  [".pdf", ".doc"]
)

JS does have Set, but there's no point to use it as you need to iterate anyways, everything in JS is ordered

CodePudding user response:

You can remove element from DOM by using Node.removeChild()

Here is an example on how to do it:

const el = document.querySelector("#myList");
el.parentElement.removeChild(el);
  • Related