Peter Series
Peter Series

Reputation: 289

getElementById(...) returns null unexpectedly

EDITED: I pretty much checked dozens of articles here on this issue, but I simply can't find the problem in my code: The line (commented below) returns null, although I expect it to return the particular element I created and added above.

    element2 = document.createElement("button");
    element2.innerHTML = "-";
    element2.text = rowCounter;
    element2.style.backgroundColor = 'white';
    element2.id = "kuerzer"+rowCounter; //rowCounter is an iterator variable
    ell2.appendChild(element2);
    console.log(document.getElementById(element2.id)); //returns null

However, I am now trying to find this element in another function like this:

function structureGantData(){
      var gantData = [[]];
      for(i=0; i<document.getElementById("myTable").rows.length; i++){
        console.log("schleife");
        gantData[i][0] = document.getElementById("kuerzer",(i+1)).text; //ISSUE

Could anyone help me? :-)

Thanks alot!

Fabian

Upvotes: 0

Views: 84

Answers (2)

obataku
obataku

Reputation: 29656

I believe you meant to call document.getElementById("kuerzer" + (i + 1)) rather than document.getElementById("kuerzer", i + 1) in structureGantData.

Upvotes: 0

zerkms
zerkms

Reputation: 255155

You have not added the created element to the DOM, so it cannot be found there.

You may use say Node.appendChild (or any other similar) method to append it somewhere first.

Upvotes: 4

Related Questions