简体   繁体   中英

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?

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.

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;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM