HTML DOM Link Object: Accessing and Manipulating Link Elements
The HTML DOM Link
object provides an interface to interact with <link>
elements within an HTML document. These elements are primarily used to link external resources such as stylesheets, favicons, and other related documents to your HTML page. Understanding how to access and manipulate these elements using JavaScript is crucial for dynamic web development and for creating customizable and responsive web experiences. This guide explores the properties and methods of the Link
object, offering practical examples to enhance your understanding and skills.
Understanding the <link>
Element
The <link>
element is an essential part of HTML, allowing you to specify the relationship between the current document and an external resource. It is commonly used for including CSS stylesheets, but can also be utilized for various other purposes, such as specifying favicons or alternate style sheets. The general structure of a <link>
element is as follows:
<link rel="stylesheet" href="styles.css" type="text/css" />
Key attributes include:
rel
: Specifies the relationship between the current document and the linked resource (e.g.,"stylesheet"
,"icon"
,"alternate"
).href
: Indicates the URL of the linked resource.type
: Specifies the MIME type of the linked resource (e.g.,"text/css"
).
Accessing <link>
Elements via the DOM
You can access <link>
elements using JavaScript through the DOM (Document Object Model). The common method is using document.getElementsByTagName()
or document.querySelectorAll()
:
// Accessing all link elements
const linkElements = document.getElementsByTagName('link');
// Accessing all link elements with specific rel attribute using querySelectorAll
const styleSheets = document.querySelectorAll('link[rel="stylesheet"]');
The linkElements
and styleSheets
variables will now hold HTMLCollection and NodeList respectively of all found <link>
elements.
Key Properties of the HTML DOM Link Object
The Link
object has several useful properties that allow you to access and manipulate information related to a link element.
Property | Type | Description |
---|---|---|
`href` | String | Returns or sets the URL of the linked resource. |
`rel` | String | Returns or sets the relationship between the current document and the linked resource (e.g., “stylesheet”, “icon”). |
`type` | String | Returns or sets the MIME type of the linked resource (e.g., “text/css”). |
`media` | String | Returns or sets the media type for which the linked resource is intended (e.g., “screen”, “print”). |
`hreflang` | String | Returns or sets the language of the linked resource. |
`sizes` | DOMTokenList | Returns or sets the sizes of the linked resource, especially useful for icons. |
`as` | String | Returns or sets the type of the content being requested via the link, such as “style” or “script”, typically used for preload or prefetch links. |
`crossOrigin` | String | Returns or sets the CORS setting for the resource loading, like “anonymous” or “use-credentials”. |
`referrerPolicy` | String | Returns or sets the referrer policy for the request associated with the link. |
`integrity` | String | Returns or sets the Subresource Integrity (SRI) hash used to verify the linked resource. |
`disabled` | Boolean | Returns or sets if the linked resource is disabled. When `true`, the browser does not load the linked resource. |
`sheet` | CSSStyleSheet | Returns the CSSStyleSheet object for the linked CSS file, if it exists and is a stylesheet. |
Practical Examples
Let’s explore how to use these properties with practical code examples.
Example 1: Accessing and Modifying a Link’s href
Property
This example demonstrates how to access and change the URL of a linked stylesheet.
<link
id="myLink"
rel="stylesheet"
href="styles_original.css"
type="text/css"
/>
<button id="changeLinkButton">Change Link URL</button>
<div id="linkOutput1"></div>
<script>
const myLinkElement1 = document.getElementById('myLink');
const changeLinkButton1 = document.getElementById('changeLinkButton');
const linkOutputDiv1 = document.getElementById('linkOutput1');
changeLinkButton1.addEventListener('click', () => {
const originalURL = myLinkElement1.href;
myLinkElement1.href = 'styles_new.css';
linkOutputDiv1.innerHTML = `Original URL: ${originalURL}<br>New URL: ${myLinkElement1.href}`;
});
</script>
Output:
Initially, the page loads styles_original.css
. After clicking the “Change Link URL” button, the link element will be updated, attempting to load styles_new.css
and also displays the change.
Example 2: Retrieving and Displaying Link Attributes
This example shows how to extract multiple attributes of a linked resource and display them on the page.
<link
id="myLink2"
rel="stylesheet"
href="styles2.css"
type="text/css"
media="screen"
/>
<div id="linkOutput2"></div>
<script>
const myLinkElement2 = document.getElementById('myLink2');
const linkOutputDiv2 = document.getElementById('linkOutput2');
const href = myLinkElement2.href;
const rel = myLinkElement2.rel;
const type = myLinkElement2.type;
const media = myLinkElement2.media;
linkOutputDiv2.innerHTML = `
href: ${href}<br>
rel: ${rel}<br>
type: ${type}<br>
media: ${media}
`;
</script>
Output:
The output div will display the href
, rel
, type
, and media
attributes of the link element as set in the HTML.
Example 3: Disabling a Link Element
This example demonstrates how to disable a linked stylesheet, effectively removing its styling from the page.
<link
id="myLink3"
rel="stylesheet"
href="styles3.css"
type="text/css"
/>
<button id="toggleLinkButton">Disable Stylesheet</button>
<div id="linkOutput3"></div>
<script>
const myLinkElement3 = document.getElementById('myLink3');
const toggleLinkButton = document.getElementById('toggleLinkButton');
const linkOutputDiv3 = document.getElementById('linkOutput3');
let disabledState = false;
toggleLinkButton.addEventListener('click', () => {
disabledState = !disabledState;
myLinkElement3.disabled = disabledState;
linkOutputDiv3.innerHTML = `Stylesheet disabled: ${disabledState}`;
toggleLinkButton.innerText = disabledState ? "Enable Stylesheet" : "Disable Stylesheet";
});
</script>
Output:
Initially, the stylesheet defined by styles3.css
will be applied. Clicking the “Disable Stylesheet” button will toggle the disabled state of the link, removing the styles from the page. The button text and the output div will also reflect the changed state.
Note: The disabled
property will prevent browser from loading or applying the link. 💡
Example 4: Accessing CSSStyleSheet Object
This example shows how to access the CSSStyleSheet
object associated with a <link>
element and display some properties of it.
<link
id="myLink4"
rel="stylesheet"
href="styles4.css"
type="text/css"
/>
<div id="linkOutput4"></div>
<script>
const myLinkElement4 = document.getElementById('myLink4');
const linkOutputDiv4 = document.getElementById('linkOutput4');
if (myLinkElement4.sheet) {
const cssSheet = myLinkElement4.sheet;
const cssHref = cssSheet.href;
const cssTitle = cssSheet.title;
linkOutputDiv4.innerHTML = `
CSS Sheet URL: ${cssHref}<br>
CSS Sheet Title: ${cssTitle || 'No title'}
`;
} else {
linkOutputDiv4.innerHTML = "No CSS sheet found or not applicable";
}
</script>
Output:
If the link is for CSS file, it will display the CSS sheet URL and title (if there is any). Otherwise, it will indicate that no CSS sheet found or is not applicable.
Example 5: Dynamic style switch using <link>
This example demonstrate how we can switch style by changing the href
attribute of the link dynamically.
<link
id="themeLink"
rel="stylesheet"
href="theme-light.css"
type="text/css"
/>
<button id="themeSwitcher">Switch to Dark Theme</button>
<div id="themeOutput"></div>
<script>
const themeLinkElement = document.getElementById('themeLink');
const themeSwitcherBtn = document.getElementById('themeSwitcher');
const themeOutputDiv = document.getElementById('themeOutput');
themeSwitcherBtn.addEventListener('click', () => {
if (themeLinkElement.href.endsWith('theme-light.css')) {
themeLinkElement.href = 'theme-dark.css';
themeSwitcherBtn.innerText = 'Switch to Light Theme';
} else {
themeLinkElement.href = 'theme-light.css';
themeSwitcherBtn.innerText = 'Switch to Dark Theme';
}
themeOutputDiv.innerHTML = `Current theme: ${themeLinkElement.href}`
});
</script>
Output:
Initially the page loads theme-light.css
. Clicking “Switch to Dark Theme” button switch the css and display the current loaded css file name. Clicking “Switch to Light Theme” button will switch back to light css theme and display the current loaded css file.
Conclusion
The HTML DOM Link
object provides comprehensive access to the <link>
elements in your HTML document. By utilizing its various properties and methods, you can dynamically manipulate and interact with linked resources, enabling you to create more flexible, responsive, and engaging web applications. Understanding these features is crucial for any web developer looking to enhance their dynamic HTML skills.