Home > Software engineering >  jQuery to move alt text to each silbling element only
jQuery to move alt text to each silbling element only

Time:06-14

I tried playing around with .append() .insertAdjacentHTML() and .insertAfter() to move each image's alt text to its sibling element, but it is not working as expected...

The target result is:
Image 1
Caption 1
Image 2
Caption 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 >
  <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=#FFFFFFFF&l=f&o=t&aim=true" alt="Example Image Caption 1" >
  <span id="here"></span>
</div>
<div >
  <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" >
  <span id="here"></span>
</div>

Greatly appreciated it if anyone could help, thanks!

CodePudding user response:

There is no one liner for this. You need to loop over the images and set the text in the loop

$(".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 >
  <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=#FFFFFFFF&l=f&o=t&aim=true" alt="Example Image Caption 1" >
  <span id="here"></span>
</div>
<div >
  <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" >
  <span id="here"></span>
</div>

Other way is to select the spans and reference the image

$(".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 >
  <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=#FFFFFFFF&l=f&o=t&aim=true" alt="Example Image Caption 1" >
  <span id="here"></span>
</div>
<div >
  <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" >
  <span id="here"></span>
</div>

  • Related