Skip to content
Advertisement

How to get innertext of heading on grid card click?

Please help me to get innerText of heading from grid card.

CSS File ;

.container1 {
  display: grid;
  grid-template-columns: auto auto auto auto;
  column-gap: 10px;
  justify-content: space-evenly;
}
.posts {
  width: 13rem;
  margin: 10px auto 10px auto;
  height: 17rem;
  background: white;
  box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
  border-radius: 10px;
}
<div class="container1">
  <div class="posts">
    <h3>Heading 1</h3>
  </div>
  <div class="posts">
    <h3>Heading 2</h3>
  </div>
  <div class="posts">
    <h3>Heading 3</h3>
  </div>
  <div class="posts">
    <h3>Heading 4</h3>
  </div>
  <div class="posts">
    <h3>Heading 5</h3>
  </div>
  <div class="posts">
    <h3>Heading 6</h3>
  </div>
</div>

How can I get innerText of heading if I click on grid3 and so on through Javascript ?

Advertisement

Answer

Assuming grids refer to the div.posts elements, you can just use the the document method querySelectorAll() to retrieve a list of all the grids, use the forEach() method to iterate through the retrieved list of grids and then add a click listener to each grid that will retrieve the heading element’s inner text.

Check and run the following Code Snippet for a practical example of the above approach:

const grids = document.querySelectorAll('div.posts');
grids.forEach(grid => grid.addEventListener('click', () => {
  console.log(grid.childNodes[0].textContent);
  alert(grid.childNodes[0].textContent);
}));
.container1 {display: grid; grid-template-columns: auto auto auto auto; column-gap: 10px; justify-content: space-evenly;}
.posts {width: 13rem; margin: 10px auto 10px auto; height: 17rem; background: white; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2); border-radius: 10px;}
<div class="container1">
  <div class="posts"><h3>Heading 1</h3></div>
  <div class="posts"><h3>Heading 2</h3></div>
  <div class="posts"><h3>Heading 3</h3></div>
  <div class="posts"><h3>Heading 4</h3></div>
  <div class="posts"><h3>Heading 5</h3></div>
  <div class="posts"><h3>Heading 6</h3></div>
</div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement