Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove all the empty anchor tags if target address in not provided and innerText prensents

I’m getting HTML template response from API service, in that sometimes I’m getting link and its href value is empty string(but innerText has some value),
Can anyone help me how can I hide the anchor tag if only text is present and href is empty.
Sometimes HTML response provides multiple empty links, give solution to hide all the empty links.

<div class="hyper-btn">
    <a href="" target="_blank"> User Profile </a>
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To hide anchor tag, by using CSS will hide the elements from document.

<!DOCTYPE html>
<html>
  <style>
    .hyper-btn a[href=""] {
      display: none !important; 
      /* will hide all the empty anchor tags */
    }
  </style>
  <body>
    <div class="hyper-btn">
        <a href="" target="_blank">Empty Link</a>
        <a href="someAddress" target="_blank">Link to some Address</a>
    </div>
  </body>
</html>

To remove anchor tags from DOM itself, add below JavaScript

<!DOCTYPE html>
<html>
<body>
    <div class="hyper-btn">
        <a href="" target="_blank">Empty Link</a>
        <a href="someAddress" target="_blank">Link to some Address</a>
    </div>

    <script>
        const linkList = document.querySelectorAll('.hyper-btn a');
        linkList.forEach(element => {
            const targetURL = element.getAttribute('href');
            if(!targetURL) {
                element.remove(); // will be removed from DOM
            }
        });
    </script>
</body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading