Very good, let's say we have a block ( div
) divided into six more. Each of these contains a img
, h2
and p
:
Then we want that, when the mouse passes over one of the images, an image appears alert
with the content of p
the same container. OKAY. Well, the only way I have found to be able to access the p
is by placing the class( evento
) in the container to access the text of p
with ( this.lastElementChild.innerHTML;
).
Something like that:
var evento = document.getElementsByClassName('evento');
var par = document.getElementsByClassName('par');
for(i = 0; i < evento.length; i++){
evento[i].addEventListener('mouseover', function(){
var texto = this.lastElementChild.innerHTML;
alert(texto);
})
}
<div id="bloque">
<div class="evento">
<img src="img/icono engranaje.png" alt="imagen A">
<h2>web designs</h2>
<p class="par">aaaaaaaaa</p>
</div>
<div class="evento">
<img src="img/icono estadistica.png" alt="imagen E">
<h2>web development</h2>
<p class="par">eeeeeeee</p>
</div>
<div class="evento">
<img src="img/icono etiqueta.png" alt="imagen I">
<h2>responsive designs</h2>
<p class="par">iiiiiiiiiiiiii</p>
</div>
<div class="evento">
<img src="img/icono nube.png" alt="imagen O">
<h2>edit sections</h2>
<p class="par">ooooooooo</p>
</div>
<div class="evento">
<img src="img/icono pause.png" alt="imagen U">
<h2>databases</h2>
<p class="par">uuuuuuuuuuuuuu</p>
</div>
<div class="evento">
<img src="img/icono perfil.png" alt="imagen EPA">
<h2>android</h2>
<p class="par">epaepaepa</p>
</div>
</div>
But I can't find a way that, by exclusively hovering over the image, I can get the text fromp
Thank you!
Option with QuerySelector :
If what you want is for the event to be activated when doing the one
hover
in the image, you can keep all the elementsimg
:querySelectorAll
returns a list of items, so you'll need to iterate through it afterwards.And to get the text, knowing the structure you can access the parent and from there get the
p
, with anotherquerySelector
, unlikequerySelectorAll
this returns the first element.snippet: