The problem is, with the line down:
var teste = $(elementos[i].className).attr('alt');
You are selecting the div
where the image is contained. So, when you capture the attribute alt
of this element, you receive nothing, since the div
has no attribute alt
.
Logo, you could fix the code by selecting the images:
var elementos = $('.pai .filho > img');
Thus remaining:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pai">
<div class='filho'>
<img alt="alt1">
</div>
<div class='filho'>
<img alt="alt2">
</div>
<div class='filho'>
<img alt="alt3">
</div>
<div class='filho'>
<img alt="alt4">
</div>
</div>
<style>
.filho {
background: black;
color: white;
margin: 20px;
text-align: center;
font-size: 28px;
font-weight: bold;
}
</style>
<script>
var elementos = $('.pai .filho > img');
var countElementos = elementos.length;
var intervalo = 1;
var comeco = 0;
for(var i = comeco; i < countElementos; i += intervalo) {
var teste = $(elementos[i]).attr('alt');
console.log(teste);
}
</script>
If you want to search for the child element within the loop for
, can do so:
var elementos = $('.pai .filho');
var countElementos = elementos.length;
var intervalo = 1;
var comeco = 0;
for(var i = comeco; i < countElementos; i += intervalo) {
// Note abaixo que adicionei o "children".
// Também removi o `className`, já que o `elementos[i]` já é suficiente para que o jQuery reconheça o elemento:
var teste = $(elementos[i]).children('img').attr('alt');
console.log(teste);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pai">
<div class='filho'>
<img alt="alt1">
</div>
<div class='filho'>
<img alt="alt2">
</div>
<div class='filho'>
<img alt="alt3">
</div>
<div class='filho'>
<img alt="alt4">
</div>
</div>
This would solve, but the logic would be to access the parent element and then get the child, in this case the alt
– Josimara
I edited the answer by adding one more example to the end. That would be it? ;)
– Luiz Felipe
Children! Exactly that, thanks!
– Josimara