Open In App

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

Last Updated : 17 Jan, 2023
Like Article

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=""></a></span>

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

<span id="outer"><a id="inner" href=""></a></span>

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


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


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


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


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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads