JavaScript Functions for SEO

Share this post

In this post, I will show you JavaScript (JS) functions that you can use to implement SEO split tests with Google Tag Manager, to automate your SEO tasks and to do data manipulation tasks.


JavaScript SEO Functions for Google Tag Manager

JavaScript SEO Functions for Browser Automation

Useful JS Functions for Data Manipulation

JavaScript Functions for Chrome DevTools Console


JavaScript SEO Functions for Google Tag Manager

Here is a collection of many useful SEO JavaScript functions that you can use with Google Tag Manager. Just note that this should be implemented for testing purposes and not as a long term deployment.

Add Nofollow to All External Links on a Page

Using Google Tag Manager, you could make an SEO Split Test to see if adding rel=nofollow to all external links helps your SEO performance or not.

<script>
function toNofollow() {
var x = document.getElementsByTagName("a");
var i;
for (i = 0; i < x.length; i++) {
if (location.hostname!=x[i].hostname){
x[i].rel = "nofollow";
}}}
mft=setTimeout("toNofollow()",0);
function LoadEvent(func){
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func;
}
else{
window.onload = function()
{
if(oldonload)
{oldonload();}
func();}}}
LoadEvent(function(){
toNofollow();
});
</script>

Modify Text of a Link Using the Index

If you want to know how it would look in your webpage to change the text of a link, you can use .textContent.

Press CTRL + Shift + J to open the JavaScript console. You can find more useful expressions here.

//Here I will change the anchor of the 2nd link in the page.

$('a')[2].textContent="New Text";

//same as the document.querySelector() function

document.querySelector('a')[2]="New Text";

Modify a Meta Description Using CSS Selector

<script>
var metaRobots = document.querySelector('meta[name="description"]');
if (!metaRobots) {
  metaRobots = document.createElement('meta');
  metaRobots.setAttribute('content', 'Your new meta description');
  document.head.appendChild(metaRobots);
}
metaRobots.setAttribute('content', 'Your new meta description');
</script>
    

Modify the Title Tag

Nothing more simple than to modify the title tag.

<script>
document.title = "New title";
</script>

Modify a H1 Tag

You can change visual elements in a page like the h1 (not that I recommend it).

const newHeadline = document.querySelector('h1');
newHeadline.textContent = "This is a new h1';

JavaScript SEO Functions for Browser Automation

Browser Automation is awesome to automate SEO tasks.

The functions I am showing you here will help you making punctual tasks at scale such as clicking on all links of a page.

For advanced SEO automation, you should use Selenium or Puppeteer. Puppeteer is faster but only works with chrome, which is why I prefer using Selenium for SEO.

Click on a Link

One of the most useful things you can do when you use JavaScript (JS) for SEO is to click on a link. You can do so using the click() function.

document.getElementById('yourLinkID').click(); //Click using ID
document.getElementsByClassName(yourLinkClass").click(); //Click using Class
document.querySelectorAll("css.slector").click(); //Click CSS Selector

Open a Page in a New Tab

The JavaScript window.open() method combined with the href and the '_blank' parameters open a new browser window to the specified URL.

window.open('https://www.jcchouinard.com', '_blank');

Get the Current Page Address (URL)

Using window.location, you can get the current page address with JavaScript.

window.location.href // Current URL (href)
window.location.hostname // Current domain name 
window.location.pathname // Current Page Path
window.location.protocol // Current web protocol used (http or https)

Useful JS Functions for Data Manipulation

Convert Permalinks to a String of Keywords

At some point in your keywords research, you might want to modify a URL into a string of words.

function urltoText(str) {
  return str.split(/\W/).join(" ");
}
urltoText("/extracted-permalink-to-change").trim();

//"extracted permalink to change"

Convert Titles to URL Slugs

The opposite is also possible. You might want to convert stuff into a list of URLs. Take a list of keywords from your keywords research or titles of blog posts, for example.

var yourPostTitle = "Title of my SEO post";

function texttoUrl(title) {
  return "/"+ title
    .toLowerCase()
    .trim()
    .split(/\s+/)
    .join("-");
}

texttoUrl(yourPostTitle);

JavaScript Functions for Chrome DevTools Console

The Chrome DevTools console can be really useful for SEOs.

View the Number of DOM elements

Is your DOM size too large for Google?

Google’s official documentation tells you that an optimal DOM tree:

  • Has less than 1500 nodes total.
  • Has a maximum depth of 32 nodes.
  • Has no parent node with more than 60 child nodes.

To look for the number of DOM nodes, you can use this function in the JavaScript Console.

document.getElementsByTagName('*').length

Get All Links Containing Href

Gather all the links in a page that contain a specific substring, and return an array.

var link = document.querySelectorAll("[href*='/blog']");
var arr = [];
for(var i = 0; i < link.length; i++){
    href = link[i].getAttribute('href');
    arr.push(href)
 };
 console.log(arr);
// ['/blog','/blog/1st-blog-post','/blog/2nd-blog-post']

Modify the Anchor Link in the Page

Return the Value of the Latest Expression

$_  //Latest Expression
5+2 
//7
$_  
//7

View The Latest Inspected Elements

If you have inspected an element using right-click > inspect. You can find it using the $0, $1, $2, $3 and $4 commands. By using $0, you’ll show the latest selected element and by using $1 you’ll get the second latest selected element.

Clear the Console

You can clear the console using the clear() function.

Conclusion

There are a lot more that you can do with JavaScript. Other programming languages are also really interesting for SEOs who want to gain technical SEO skills.

Check out this complete series to help you learn python for Search Engine Optimization (SEO).