Matthew Sirkin Matthew Sirkin - 1 month ago 6
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 = "http://www.enviroptics.com/"; //Cannot set property 'href' of null(…)


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

JSfiddle for full code: http://jsfiddle.net/98oL12tk/17/ Lines 106-109 in JS section.

Answer

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 = 'http://www.enviroptics.com/';

Comments