How to get the value of the type attribute of a link in JavaScript?

To get the value of the type attribute of a link in JavaScript, use the type property. The type attribute specifies the MIME type of the linked document, such as "text/html" for HTML documents or "text/css" for stylesheets.

Syntax

element.type

Example: Getting Link Type Attribute

You can access the type attribute of a link using getElementById() and the type property:

<!DOCTYPE html>
<html>
<body>
   <p><a id="anchorid" type="text/html" target="_blank" href="https://www.tutorialspoint.com/">TutorialsPoint</a></p>
   
   <script>
      var myVal = document.getElementById("anchorid").type;
      console.log("Value of type attribute: " + myVal);
      
      // Display in the page
      document.body.innerHTML += "<p>Type attribute value: " + myVal + "</p>";
   </script>
</body>
</html>
Value of type attribute: text/html

Common Type Attribute Values

Here are typical MIME type values used with links:

<!DOCTYPE html>
<html>
<body>
   <p><a id="htmlLink" type="text/html" href="/page.html">HTML Link</a></p>
   <p><a id="cssLink" type="text/css" href="/styles.css">CSS Link</a></p>
   <p><a id="jsLink" type="application/javascript" href="/script.js">JS Link</a></p>
   
   <script>
      console.log("HTML link type:", document.getElementById("htmlLink").type);
      console.log("CSS link type:", document.getElementById("cssLink").type);
      console.log("JS link type:", document.getElementById("jsLink").type);
   </script>
</body>
</html>
HTML link type: text/html
CSS link type: text/css
JS link type: application/javascript

Checking if Type Attribute Exists

Not all links have a type attribute. You should check if it exists before accessing it:

<!DOCTYPE html>
<html>
<body>
   <p><a id="withType" type="text/plain" href="/file.txt">Link with type</a></p>
   <p><a id="withoutType" href="/page.html">Link without type</a></p>
   
   <script>
      function getTypeAttribute(linkId) {
         var link = document.getElementById(linkId);
         var typeValue = link.type;
         
         if (typeValue) {
            console.log(linkId + " type: " + typeValue);
         } else {
            console.log(linkId + " has no type attribute");
         }
      }
      
      getTypeAttribute("withType");
      getTypeAttribute("withoutType");
   </script>
</body>
</html>
withType type: text/plain
withoutType has no type attribute

Conclusion

Use the type property to get the MIME type of a link element. Always check if the attribute exists before using it, as not all links include this optional attribute.

Updated on: 2026-03-15T23:18:59+05:30

610 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements