Bill
Bill

Reputation: 71

How to fix textContent as undefined inside of for loop?

When i run the code below, it says "Cannot read property 'textContent' of undefined". Even onclick, addEventListener, length and much more says undefined! How can i fix this?

Here's the code:

<div id = "dropdown-content" class = "d-con">
    <a href = "#">America</a>
    <a href = "#">Canada</a>
    <a href = "#">Rio</a>
</div>

And The javaScript:

(function(){
    var i;
    var dropdown = document.getElementsByClassName('d-con');
    for(i = 0; i <= dropdown.length; i = i + 1){
        alert(dropdown[i].textContent);
    }
}()); 

Upvotes: 1

Views: 1224

Answers (4)

cнŝdk
cнŝdk

Reputation: 32145

Your only problem here is that your i counter reaches dropdown.length and dropdown[dropdown.length] is undefined, in other words you are trying to access an undefined element in the dropdown array.

That's why your code alerts the first 3 elements then throws the error, when it tries to access this undefined element.

Solution:

In the for loop your condition should be i < dropdown.length and not i <= dropdown.length.

(function() {
  var i;
  var dropdown = document.getElementsByClassName('d-con');
  for (i = 0; i < dropdown.length; i++) {
    alert(dropdown[i].textContent);
  }
}());

Demo:

(function() {
  var i;
  var dropdown = document.getElementsByClassName('d-con');
  for (i = 0; i < dropdown.length; i++) {
    alert(dropdown[i].textContent);
  }
}());
<div id="dropdown-content" class="d-con">
  <a href="#">America</a>
  <a href="#">Canada</a>
  <a href="#">Rio</a>
</div>

Upvotes: 3

Kartik Chauhan
Kartik Chauhan

Reputation: 3068

If div with id dropdown-content is the only element that contains class d-con, then grab the element by using getElementById or you can simply alert the content without using any loop by writing alert(dropdown[0].textContent);

Upvotes: 0

Rupali Pemare
Rupali Pemare

Reputation: 540

Just check this

    (function(){
      $('.d-con a').each(function(key, value){
        console.log(value.textContent);
      });
    }()); 

Upvotes: 0

Nirav Joshi
Nirav Joshi

Reputation: 2960

Here try to check this code.

No need to make a loop for inner elements.

(function(){
        var i;
        var dropdown = document.getElementsByClassName('d-con');
        alert(dropdown[0].textContent);
    }());
<div id = "dropdown-content" class = "d-con">
        <a href="#">America</a>
        <a href="#">Canada</a>
        <a href="#">Rio</a>
    </div>

Upvotes: 1

Related Questions