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

Answer

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>

Leave a Reply

Your email address will not be published. Required fields are marked *