sebas.varela
sebas.varela

Reputation: 1565

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

I want to get the text of the paragraph (p) contained in div by clicking on that div using the class name. I tried using innerText and innerHTML but it returns undefined in the console. How can I do it using only 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?
   });
});

Upvotes: 0

Views: 648

Answers (2)

CubeDev
CubeDev

Reputation: 155

If you want to get text inside all the paragraphs having "paragraphs" class, this code can also help you:

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

Upvotes: 0

ShinaBR2
ShinaBR2

Reputation: 2705

Working example: https://codepen.io/shinaBR2/pen/qBbxRgz Basic code is

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

Upvotes: 2

Related Questions