Traté de jugar con .append() .insertAdjacentHTML() y .insertAfter() para mover el texto alternativo de cada imagen a su elemento hermano, pero no funciona como se esperaba...
El resultado objetivo es:
Imagen 1
Título 1
Imagen 2
Título 2
var altText = $("img").attr("alt"); $("span#here").append(altText); .wrap { margin-bottom: 10px; } .demo-img { width: 280px; } span#here { display: block; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrap"> <img src="https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4Y5jq?ver=ac72&q=90&m=6&h=201&w=358&b=%23FFFFFFFF&l=f&o=t&aim=true" alt="Example Image Caption 1" class="demo-img"> <span id="here"></span> </div> <div class="wrap"> <img src="https://cdn-dynmedia-1.microsoft.com/is/image/microsoftcorp/gldn-M365-CP-Microsoft365-Commercial?wid=380&hei=213&fit=crop" alt="Example Image Caption 2" class="demo-img"> <span id="here"></span> </div>Se lo agradezco mucho si alguien puede ayudar, ¡gracias!
No hay un forro para esto. Debe recorrer las imágenes y configurar el texto en el bucle.
$(".wrap img").each(function (_, img) { const alt = img.alt; $(img).next("span").text(alt); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrap"> <img src="https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4Y5jq?ver=ac72&q=90&m=6&h=201&w=358&b=%23FFFFFFFF&l=f&o=t&aim=true" alt="Example Image Caption 1" class="demo-img"> <span id="here"></span> </div> <div class="wrap"> <img src="https://cdn-dynmedia-1.microsoft.com/is/image/microsoftcorp/gldn-M365-CP-Microsoft365-Commercial?wid=380&hei=213&fit=crop" alt="Example Image Caption 2" class="demo-img"> <span id="here"></span> </div>Otra forma es seleccionar los tramos y hacer referencia a la imagen.
$(".wrap span").text(function() { return $(this).prev('img').attr('alt'); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrap"> <img src="https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4Y5jq?ver=ac72&q=90&m=6&h=201&w=358&b=%23FFFFFFFF&l=f&o=t&aim=true" alt="Example Image Caption 1" class="demo-img"> <span id="here"></span> </div> <div class="wrap"> <img src="https://cdn-dynmedia-1.microsoft.com/is/image/microsoftcorp/gldn-M365-CP-Microsoft365-Commercial?wid=380&hei=213&fit=crop" alt="Example Image Caption 2" class="demo-img"> <span id="here"></span> </div>