If you are a designer or developer engaged in affiliate marketing, you always need to put your affiliate link in your content. And in some links on your content may be mixed with anchors that should have rel="sponsored,nofollow" and shouldn't.

Adding the rel attribute to blog posts should be easy from the CMS text editor.

Previously, I got an idea to add this rel attribute automatically from the frontend side. Especially if you use URL cloaking for your affiliate links.

You should be able to find all the anchor tags with the value that has prefix is your cloaking URL.

For example, if your cloaking URL is https://yourdomain.com/go/some-product we can use the https://yourdomain.com/go/ as the prefix to get the anchors from the page.

By using javascript, you can use this code

const x = document.querySelectorAll(
    "a[href^='https://yourdomain.com/go']"
);

x.forEach(link);

function link(x) {
    x.setAttribute("rel", "sponsored,nofollow");
}
  • As you can see we are using the ^ symbol for the attribute selector, which means "Selects every <a> element whose href attribute value begins with 'https://yourdomain.com/go' "
  • By using forEach we then add a new attribute.

Here are the references for the other selector symbols to match your need:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

Detail reference:

CSS Attribute Selector

Share

Let me know your thought or you find a mistake/outdated content for this post.

Get the latest update of tutorials, inspirations and useful resources for website design and development to your email box