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

Time:09-28

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 >
    <a href="" target="_blank"> User Profile </a>
</div>

CodePudding user response:

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 >
        <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 >
        <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>

  •  Tags:  
  • html
  • Related