Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to change span content within a div

How do I change the span content when a div block is clicked using JavaScript?

var tiles = document.querySelector(".block2");
tiles.addEventListener("click", function() {
  document.getElementsByClassName(".txt").innerHTML = "Hello";
});
<div class="block1"><span class="txt">1</span></div>
<div class="block2"><span class="txt">2</span></div>
<div class="block3"><span class="txt">3</span></div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to

  • get all blocks
  • loop them
  • add a click to each
  • get the inner spans of the current block
  • loop them
  • change the innerText
var tiles = document.querySelectorAll(".block1, .block2, .block3");
for (let tile of tiles) tile.addEventListener("click", function() {
  for (let span of tile.querySelectorAll(".txt")) span.innerHTML = "Hello";
});
<div class="block1"><span class="txt">1</span></div>
<div class="block2"><span class="txt">2</span></div>
<div class="block3"><span class="txt">3</span></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading