1

Can somebody please help me why I have in console 2 times undefined? And how can I fix this? T

const intro = document.querySelectorAll('.intro');

for (i = 0; i < intro.length; i++) {
  console.log(intro[i].innerContent);
}
<div class="intro">The DOM is very useful.</div>
<div class="intro">This example demonstrates the method.</div>
Andy
  • 61,948
  • 13
  • 68
  • 95
  • 4
    There's no attribute called `innerContent`. Use [`textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent), or [`innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText). They [do have differences](https://stackoverflow.com/questions/35213147/difference-between-textcontent-vs-innertext). – Andy Jun 08 '21 at 19:03

2 Answers2

1

I think you want to use the innerText property (possibly innerHTML). There is also a textContent property, but that is probably not what you want because it gets non-human-readable text content including the contents of style and script tags.

const intro = document.querySelectorAll('.intro');
for (i = 0; i < intro.length; i++) {
  console.log(intro[i].innerText);
}
<div class="intro">The DOM is very useful.</div>
<div class="intro">This example demonstrates the method.</div>
Paul Wheeler
  • 18,988
  • 3
  • 28
  • 41
  • Thank you for correction. I have one more question: If I want use method .getElementsByClassName() instead and than print innerText from every element that uses class intro. How it would be? Thank you for your help. – Christian Angyal Jun 09 '21 at 08:43
  • The `getElementsByClassName()` function would work very similarly: `document.getElementsByClassName('intro')`, just note that you do not include the dot before the class name (i.e. you want `'intro'` not `'.intro'`) – Paul Wheeler Jun 09 '21 at 20:35
0

Because no property called innerContent exists for html elements, and attempting to access properties that don't exist always returns undefined in Javascript. You're probably looking for .textContent.

peabrainiac
  • 998
  • 9
  • 16