Open In App

How to hide span element if anchor href attribute is empty using JavaScript ?

Last Updated : 17 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The task is to hide the <span> tag when href attribute of <a> tag is not present or invalid.

Let us consider we have <a> tag inside the <span> tag. It will look similar to this:

<span><a href="www.google.com"></a></span>

Now we add the id to the elements to identify them.

<span id="outer"><a id="inner" href="www.google.com"></a></span>

Now, we have to hide the <span> tag when the “href” attribute of <a> tag is empty or invalid. 

Approach:

  • The first case is when href is empty. So we just need to check for empty href which can be done using vanilla JavaScript.
  • In the second case, the href is pointing to a file/location. We need to check if it is a valid file/location or not. Now in this case when href is present then we check if it points to some valid file or location. We will do it using jQuery Ajax call. The jQuery Ajax call can be used to exchange data with a web server behind the scenes. If it returns an error then the location of the file is invalid.

Example 1: The below code shows when the href is empty.

HTML




<span id="outer">
    <a id="inner" href="">this is link</a>
</span>
  
<script>
    if(document.getElementById("inner")
                .getAttribute("href")=="") {
        document.getElementById("outer")
                  .style.display = "none";
        alert("File does not exist");
    }
</script>


Output:

Example 2: Below code is an example when href points to a location.

HTML




<script src=
</script>
  
<span id="outer">
    <a id="inner" 
       href=
        this is link
    </a>
</span>
  
<script>
    // Function to check if url is
    // valid by making Ajax call
    function doesFileExist(url) {
        $.ajax({
            headers:{    
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*' 
            },
            method:'HEAD',
            url:url,
            success:function(){
                alert("File exists!")
            },
            error:function(){
                // Hiding the outer span tag
                $("#outer").hide() 
                alert("File does not exists!")
            },
        })
    }
      
    // Storing the location href is pointing to
    url=$("#inner").attr("href") 
    doesFileExist(url)
</script>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads