Uncaught SyntaxError: Invalid or unexpected token in Html button

Tags: ,

I create a button dynamically through javascript. When I click on it I get the mentioned error.

The button is created like this:

var button = document.createElement("Button");
            button.setAttribute("onclick", "FollowUser('" + name + "')");
            button.setAttribute("id", "FollowUserButton");

When debugging it, I’ve tried to figure out what goes wrong when I create it. It seems to be in the part where I make the onclick event. Nothing seems odd when I set the id.

This output is returned:

button {disabled: false, form: null, formAction: “https://localhost:44398/Home/UserProfile?name=Test”, …}


I’m providing my solution by presuming few things here. Please make sure to make the suitable changes in your code. The below code snippet will provide a base to the answer you want.

let name = "foo";

var button = document.createElement("BUTTON");
var text = document.createTextNode("Click me");

button.setAttribute("onclick", `FollowUser('${name}')`);
button.setAttribute("id", "FollowUserButton");

// Append this button to a node. For instance, append it to the body.

// Function added for testing onclick event.
function FollowUser(str) {

I’m using template literals here to make the code more readable and less chaotic.

Source: stackoverflow