user3052776
user3052776

Reputation: 49

How do I use variables in document.getElementById

I have this code which I've been trying to fix for hours.

<script language="JavaScript">
    <!--

    function generate(){
    var titels = new Array();
    var i = 0;
    for(i;i<9;i++){
    var test = 'h1-0'+ i;
        titels[i] = document.getElementById(test).textContent;
    }

    document.getElementById("uitkomst").value = titels[1];      
    }
    -->
</script>

This gives me the error

TypeError: document.getElementById(...) is null
titels[i] = document.getElementById(test).textContent;

But when I change 'h1-0'+i by 'h1-0'+5 it does work and I don't get an error, so how do I fix this? Why is Javascript so annoying when using variables?

Upvotes: 2

Views: 14236

Answers (2)

jfriend00
jfriend00

Reputation: 707218

There are a couple ways you can fix this issue - you can test for a missing object and skip that case or you can catch the exception that is thrown and act accordingly in the exception handler.

Here's how you could handle missing objects in your code:

function generate(){
    var titels = [];
    var i, item, test;
    for (i = 0; i < 9; i++) {
        test = 'h1-0'+ i;
        item = document.getElementById(test);
        if (item) {
            titels[i] = item.textContent;
        }
    }
    document.getElementById("uitkomst").value = titels[1];      
}

If, this is really all your code is doing, then you don't need the for loop because you're only using the [1] item from the array and you can do this:

function generate() {
    var item = document.getElementById("h1-01");
    if (item) {
        document.getElementById("uitkomst").value = item.textContent;
    }

}

Upvotes: 0

Pointy
Pointy

Reputation: 413702

Add another variable:

  var element;

and use it in the loop to hold on to the result of fetching (or trying to fetch) the element:

for (i; i < 9; i++) {
  element = document.getElementById('h1-0' + i);
  if (element) {
    titles[i] = element.textContent;
  }
  else {
    console.log("Element " + i + " not found.");
  }
}

Then check the console to see which one is missing.

Upvotes: 1

Related Questions