Search code examples
javascriptseo

How to set SEO-Friendly onclick events for javascript created elements without event listeners?


I'm implementing a framework-less SPA in pure JS.

Google Search Engine youtube channel recommends strictly avoiding javascript event handlers. Instead, one should use the onclick property and History-API approach:

enter image description here

However, I'm creating my element entirely through javascript:

const setViewState = function(entry, parentRoot){
    const element = document.createElement("a")
    element.href = entry.href
    element.innerHTML = `${entry.id} - ${entry.content}`
    element.id = `entry${entry.id}`
    
    parentRoot.appendChild(element)
}

How do I setup an onclick function on that javascript-created element without relying on event listeners?

I tried using element.onclick = function approach but it does not seem to generate an element with onclick prop. It seems to attach a click event listener:

enter image description here

Compare it to an element hardcoded to the HTML with the onclick the video refers:

enter image description here


Solution

  • After asking martin split himself on twitter, I'm convinced there's no issues on attaching event listeners as onlick to links for rendering content.

    However, you need to indicate your route through href. And that rounting cannot be done through event listeners.

    This is his original answer:

    The point of the sample code was just to explain that there must be an href with a resolvable URL. Googlebot doesn't care about event handlers and doesn't care about event listeners either, so use either at your own discretion :)