Matthew Sirkin Matthew Sirkin - 9 months ago 43
Javascript Question

generate href for a link based on id using javascript

I'm trying to use JavaScript to create an ID for my links and also to tell it where to link to.

My JavaScript has generated a link element in my HTML:

<a id = "NB4-CAXL-14U-12-AAG"> Link Text </a>

And that appears as it should.

I then have a variable eopartnum[i]:

console.log(eopartnum[i]); //output: NB4-CAXL-14U-12-AAG

This variable matches my ID for my link above. Then i tried to access that link via the ID and assign an href to it, like so:

var linktoprod = document.getElementById(eopartnum[i]);
console.log(linktoprod); //returns null
linktoprod.href = ""; //Cannot set property 'href' of null(…)

Why does my linktoprod come up as null? Is my syntax wrong?

JSfiddle for full code: Lines 106-109 in JS section.

Answer Source

The problem is that you are calling getElementById() before you append the table to the document. At the time that you are querying for the ID, it doesn't yet exist. This example seems a bit contrived; I think you could just set firstcelllink.href = '';