Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
Javascript Alerting DIV content on click button/url

Hi so I'm trying to understand and learn Javascripting. I was challenged to find out how to alert the content of each individual onclick. Using a loop.

So I started to scratch my head and try multiple approaches. I did manage to get the content alerted but unfortunately without a clickevent.

function raport()
document.querySelectorAll(".fake").forEach(div=>{
text+=div.textContent;
});
alert(text);
}

Used a query selector to search for the class name .fake followed by div=>text.div.textcontent making variable text = to the div's content. Upon loading the page, the browser succesfully alerts the div content as seen on the html page.

BUT when I try to use a onclick event to trigger the loop upon clicking a button..

Nothing happens..

I thought of adding a buton with a specific id combined with the code:

document.getElementById('demo').onclick = function() {raport()}

The HTML button:

<button id= "demo" onclick="raport()">Klik</button>

As a means to get it done, but I'm not getting any errors nor any alerts with the content.

I also guess this isn't the most productive way to accomplish the challenge. As I'm supposed to alert each individual Meaning that I would have copy the code with unique button id's and div classes to get the right results.

Any tips on how I could get the clickevent working?

Any help would be much appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I always suggest delegation if you want to click each "fake"

And a map if you want to get a list of stuff

window.addEventListener("load", function() { // when the page loads
  const res = document.getElementById("res");
  const fakes = document.querySelectorAll("#demo .fake");
  document.getElementById("demo").addEventListener("click", function(e) {
    const tgt = e.target;
    if (tgt.classList.contains("fake")) {
      res.textContent = tgt.textContent;
    }
  });
  document.getElementById("klik").addEventListener("click", function() { 
    res.innerHTML = [...fakes] // cast the html collection to an array
      .map(fake => fake.textContent) // map the content
      .join(","); 
      
  })
});
<div id="demo">
  <div class='fake'>Hello</div>
  <div class='fake'>Man</div>
</div>
<button type="button" id="klik">Klik</button>
<hr/>
<div id="res"></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Just as a demonstration then close the question, it is a typo error:

let text ='';
function raport() {
  text = ''; // add this if you want clean variable everytime click, or just declare into function the variable
  document.querySelectorAll(".fake").forEach(div => {
    text += div.textContent;
  });
  alert(text);
}

document.getElementById('demo').onclick = function() {
  raport()
}
<button id="demo" onclick="raport()">Klik</button>
<div class='fake'>Hello</div>
<div class='fake'>Man</div>


Example of your comment:

document.querySelectorAll('.fake').forEach(el =>{
  el.addEventListener('click', () =>{
    alert(el.textContent);
  });
});
<div class='fake'>Hello</div>
<div class='fake'>Man</div>
<div class='fake'>test2</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda