Anatoly Lindemann
Anatoly Lindemann

Reputation: 54

Cannot read property 'textContent' of undefined in JavaScript

What is the problem? I declared variable n

var n = 0;

while (true) {
  var comment = document.getElementsByClassName('wall_reply_text')[n].textContent;
  
  if (comment.indexOf("публикации") == 0) {
    alert(comment);
  }
  
  n++;
}

Upvotes: 1

Views: 1312

Answers (2)

mplungjan
mplungjan

Reputation: 178350

You need to break if there is no element

var n = 0, comment=""

while (true) {
  const div = document.getElementsByClassName('wall_reply_text')[n]
  if (div) comment = div.textContent;
  else break
  
  if (comment.indexOf("публикации") == 0) {
    console.log(n,comment);
  }
  
  n++;
}
<div class="wall_reply_text">1</div>
<div class="wall_reply_text">публикации</div>
<div class="wall_reply_text">3</div>
<div class="wall_reply_text">4</div>

Here is a more elegant way

[...document.querySelectorAll('.wall_reply_text')]
  .map(div => div.textContent)
  .forEach((comment,i) => {
    if (comment.indexOf("публикации") == 0) {
      console.log(i,comment);
    }
})
<div class="wall_reply_text">1</div>
<div class="wall_reply_text">публикации</div>
<div class="wall_reply_text">3</div>
<div class="wall_reply_text">публикации</div>

Alternative if you just need the one index

const comments = [...document.querySelectorAll('.wall_reply_text')]
  .map(div => div.textContent)
console.log(comments.indexOf("публикации"))
<div class="wall_reply_text">1</div>
<div class="wall_reply_text">публикации</div>
<div class="wall_reply_text">3</div>
<div class="wall_reply_text">4</div>

Upvotes: 0

Ethan Lipkind
Ethan Lipkind

Reputation: 1156

the most likely explanation is that there are no elements with class name wall_reply_text when this code runs, so document.getElementsByClassName('wall_reply_text') returns an empty array. when you try to access index 0 in that empty array, you get undefined, and thus the error when trying to access undefined.textContent.

Upvotes: 1

Related Questions