Question

I am altering a P element on a page by calling it's id with a javascript function and I am trying to call another javascript function called closeWindow from the HREF of a .innerHTML like below.

document.getElementById("link").innerHTML = "<p>You may close this window <a href="javascript:closeWindow();">here</a></p>"

However the javascript:closeWindow is not getting called or I should say is not even being read at all and the function fails.

Any suggestions would be appreciated

Was it helpful?

Solution

Your quotes are negating one another, as you can see in the code view. Use single quotes or escape your double quotes:

document.getElementById("link").innerHTML = "<p>You may close this window <a href='javascript:closeWindow();'>here</a></p>"

OTHER TIPS

how about giving the javascript function some variables like this?

var myvar=123;
document.getElementById("link").innerHTML = "<p>You may close this window <a href='javascript:closeWindow("+myvar+",sometext);'>here</a></p>";

the myvar works, but i can't get sometext to work.

this did not work:

var mytxt='sometext'; 
var myvar=123;
    document.getElementById("link").innerHTML = "<p>You may close this window <a href='javascript:closeWindow("+myvar+","+mytxt+");'>here</a></p>";

Please some help, i get the error reference error: sometext is not defined. It thinks sometext is a variable. Putting sometext in double quotes is resulting to an empty field after the comma and a syntax error.

Found the answer:

var mytxt='sometext'; 
    var myvar=123;
        document.getElementById("link").innerHTML = "<p>You may close this window <a href='javascript:closeWindow("+myvar+",\""+mytxt+"\");'>here</a></p>";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top