View Full Version : Cannot insert a <a href=""> into a div using innerhtml

01-20-2012, 11:43 PM

I am trying to use JavaScript to change the content of a div on my page...

By clicking on a button on the side, the text content of a div changes to describe the link and at the bottom of the text I want a link to a site to appear.. The text bit is fine but I cannot find a way of inserting an <a href> in there without unexpected syntax and illegal tag errors popping up!

I thought this would be simple, (It probably is and I am just being an arse)...
I have spent ages searching for solutions and tried everything I can think of but no luck :(

So, here is the code...

function change()
document.getElementById("text").innerHTML = "lots of text<br><a href="linktonewpage">some text</a>";

I did think that separating the link away from the text and putting it in a separate div might work but still no luck. I am pretty sure that it must be the quotation marks (or the =) surrounding the link but I don't know what I can do to sort that... A link needs to be surrounded by "" doesn't it???

Any help on this would be very appreciated as I am driving myself mad here!
I apologise if this is super simple and I just being a 'noob' I really have spent hours trying to sort it!

Many thanks

01-20-2012, 11:55 PM
did you try with single quotes inside the double:

document.getElementById("text").innerHTML = "lots of text<br><a href='linktonewpage'>some text</a>";

although the thing to do really I think would be to put it into a separate div with style="display:none" (or that in css) and then

function change()

or visibilty:hidden/visible if that works better, instead of creating a link with innerHTML

01-21-2012, 02:45 AM
The quotation marks are ending your string. You can either:
a) Wrap the string in single quotes (you can place single quotes inside double quotes or vice versa and they will not end your string)

document.getElementById("text").innerHTML = 'lots of text<br><a href="linktonewpage">some text</a>';
b) Wrap the URL in single quotes (as xelawho suggested)

document.getElementById("text").innerHTML = "lots of text<br><a href='linktonewpage'>some text</a>";
c) Escape the quotation marks with a backslash

document.getElementById("text").innerHTML = "lots of text<br><a href=\"linktonewpage\">some text</a>";

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum