0

This is my code,

var baseurl = "https://localhost:8888/files/";

var mydiv = document.getElementById("myDiv"); 
var aTag = document.createElement('a');
aTag.setAttribute('href',"#");
aTag.setAttribute('onclick',"getFolderList(" + baseurl + ")"); 
aTag.innerHTML = "Home /";
mydiv.appendChild(aTag);

Here, getFolderList is the JavaScript function which accepts one parameter. I used the above code, but it does not call the function. How to pass the "baseurl" value to the getFolderList function?

1 Answer 1

3

You forgot to include quotes:

aTag.setAttribute('onclick',"getFolderList('" + baseurl + "')");
                                           ^               ^

The way you have written it, the engine will treat https://localhost:8888/files/ as the variable name, which of course would cause a syntax error.

Finally, you should avoid writing code like this inside HTML attributes - it could lead to script injection attacks if baseurl comes from an external source. Use the event listener syntax instead:

aTag.addEventListener("click", function() {
    getFolderList(baseurl);
});
Sign up to request clarification or add additional context in comments.

3 Comments

You have my +1 after the edit. IMO the second part of the answer should really be first.
Actually it's more a syntax error than a variable name :-)
@Bergi Good point - updated. Jon, agreed! But felt it important to actually answer the question as well as highlight the issues with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.