Reputation: 1565
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
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
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