Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
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>

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

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>

about 4 years ago · Santiago Gelvez Report

0

You need to fetch all divs. You can use for example this selector: document.querySelectorAll('[class^="block"]'); Then you can assign ervery div a click event.

const divs = document.querySelectorAll('[class^="block"]');

divs.forEach(d => {
  d.addEventListener("click", () => {
    d.firstChild.innerHTML = "Hello";
  });  
})
div {
  height: 20px;
  background: gray;
  padding: 5px;
  margin: 5px;
  width: 300px;
}
<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>

about 4 years ago · Santiago Gelvez Report

0

if you want to change all span innerText then,

let spans = document.getElementsByClassName("txt");

spans.forEach(element => {
  element.innerText = "Hello";
});
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!