...

View Full Version : document.getElementById as a variable in xhtml



Martins
03-02-2012, 12:51 PM
I am trying to insert some new links using ‘innerHTML’. As there may be a number of calls on the same ‘ids’ I thought it would be wise to use variables. The following does not respond beyond the alert? The process works fine if I don’t use ‘var link’ and just enter it in full. Is there an issue perhaps trying to do this with xhtml?

Thanks.


var newlink = '<a title="new link" href="newlink.htm">New Link</a>';
var link = "document.getElementById('idlink')";

if( link ) {
alert("link confirmed");
link.innerHTML = newlink;
}

devnull69
03-02-2012, 01:52 PM
document.getElementById() is a Javascript command and will not work if put into quotes. Just omit the string delimiter quotes around this command!

Martins
03-02-2012, 02:47 PM
Thanks devnull69.

I started without the quotes, but then I'm not even getting as far as a response to the alert?

ckeyrouz
03-02-2012, 02:55 PM
Post full code.

Maybe the HTML tag with id 'idlink' does not exist in your file.

Post the full code so we can help.

Martins
03-02-2012, 03:52 PM
Thanks ckeyrouz.

This was more or less the problem. I was assigning the 'var link' in the head of the document. If I assign it further down the page after the element it works fine.

Presumably if I put the variable in an external.js this will also have to be loaded after the element?

ckeyrouz
03-02-2012, 04:14 PM
Yes, you should assign your variable and your code after the load of the page.

You can put either after the element or in a window.onload in an external js file like this:



window.onload = function() {
var newlink = '<a title="new link" href="newlink.htm">New Link</a>';
var link = "document.getElementById('idlink')";

if( link ) {
alert("link confirmed");
link.innerHTML = newlink;
}
}

Martins
03-02-2012, 04:55 PM
Thank you.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum