如何使用Javascript获取名称为class的几个段落的值?

How to get the value of several paragraphs with the class name using Javascript?

我想通过使用 class 名称单击 div 来获取包含在 div 中的段落 (p) 的文本。我尝试使用 innerTextinnerHTML 但它在控制台中 returns undefined 。我怎样才能只使用 Javascript?

HTML

<div class="showName">
   <p class="paragraphs">Text 1</p>
</div>
<div class="showName">
   <p class="paragraphs">Text 2</p>
</div>
<div class="showName">
   <p class="paragraphs">Text 3</p>
</div>

Javascript

const showName = document.getElementsByClassName('showName');
const paragraphs = document.getElementsByClassName('paragraphs');

Array.prototype.forEach.call(showName, function(element) {
   element.addEventListener('click', function() {
      // How can I do it here?
   });
});

工作示例:https://codepen.io/shinaBR2/pen/qBbxRgz 基本代码是

Array.prototype.forEach.call(showName, function(element) {
   element.addEventListener('click', function() {
      // How can I do it here?
     const text = element.querySelector('.paragraphs').textContent;
     alert(text);
   });
});

如果你想在所有带有“paragraphs”class的段落中获取文本,这段代码也可以帮助你:

HTML

<div class="showName">
   <p class="paragraphs">Text 1</p>
</div>
<div class="showName">
   <p class="paragraphs">Text 2</p>
</div>
<div class="showName">
   <p class="paragraphs">Text 3</p>
</div>

JAVASCRIPT

const showName = document.getElementsByClassName('showName');
const paragraphs = document.getElementsByClassName('paragraphs');

for(i=0; i < paragraphs.length; i++){
    console.log(paragraphs[i].innerText);
}