Skip to content
Related Articles

Related Articles

HTML | DOM Link Object

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Jul, 2022
View Discussion
Improve Article
Save Article

HTML DOM Link Object is used to access HTML <link> element.
Syntax: 

  • To Access a HTML element: 
document.getElementById("myLink");  
  • To Create a New HTML element: 
document.createElement("LINK"); 

Property Values:  

Value Description
charset It assigns the character encoding of the linked document
crossOrigin It assigns the the CORS settings of the linked document
disabled It assigns whether the linked document is disabled, or not
href It is used to set/return the URL of the linked document
hreflang It assigns the language code of the linked document
media It assigns the media type for the link element
rel It assigns the relationship between the current document and the linked document
rev It assigns the reverse relationship from the linked document to the current document
sizes Returns the sizes attribute’s value of the linked resource
type It is used to set/return the content type of the linked document

Example-1: Accessing link element.  

html




<!DOCTYPE html>
<html>
 
<head>
    <link id="linkid"
          rel="stylesheet"
          type="text/css"
          href="styles.css">
</head>
 
<body>
    <h1>TO ACCESS LINK ELEMENT:</h1>
 
     
 
 
<p>PRESS THE BUTTON TO GET THE URL
      OF THE LINKED DOCUMENT.</p>
 
 
 
 
    <button onclick="gfg()">Get URL
  </button>
 
    <p id="pid"></p>
 
 
 
 
    <script>
        function gfg() {
           
            // Access link element.
            var NEW = document.getElementById(
              "linkid").href;
            document.getElementById(
              "pid").innerHTML = NEW;
        }
    </script>
 
</body>
 
</html>


Output:
Before clicking: 
 

After clicking: 
 

Example-2: Create link element. 

html




<!DOCTYPE html>
<html>
 
<head>
</head>
 
<body>
    <h1>TO CREATE A LINK ELEMENT.</h1>
 
    <button onclick="myFunction()">Create</button>
    <p id="pid"></p>
 
 
 
    <script>
        function myFunction() {
           
            // Create link element.
            var NEW = document.createElement(
              "LINK");
           
            // set attributes.
            NEW.setAttribute("id", "linkid");
            NEW.setAttribute("rel", "stylesheet");
            NEW.setAttribute("type", "text/css");
            NEW.setAttribute("href", "styles.css");
            document.head.appendChild(NEW);
 
            var NEW1 = document.getElementById(
              "linkid").href;
            document.getElementById("pid").innerHTML =
              NEW1;
 
        }
    </script>
 
</body>
 
</html>


Output:
Before clicking: 
 

After clicking: 
 

Supported Browsers: 

  • Chrome
  • Firefox
  • Internet Explorer
  • Safari
  • Opera

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!