To add a canonical link to an HTML document using JavaScript, you can use the DOM (Document Object Model) to create a <link>
element and add it to the <head>
section of your page. The canonical link should point to the preferred URL for the content on the page.
Here's an example of how to add a canonical link using JavaScript:
index.tsx258 chars7 lines
In this example, we create a new <link>
element, set its rel
attribute to 'canonical'
, and set its href
attribute to the preferred URL for the content. We then find the <head>
element of the page using document.getElementsByTagName('head')[0]
, and append the new <link>
element to it using head.appendChild(canonicalLink)
.
By adding a canonical link to your page, you can help search engines understand the preferred URL for your content and avoid potential duplicate content issues.
gistlibby LogSnag