简体   繁体   中英

Getting the title of an image and display it as HTML using JQuery

I have a img which is displaying fine, however I now want to hide the image (display: none) and get the value of its title and display that in its parent div instead, using JQuery. I'm sure it's relatively simple, I'm just drawing a massive mind blank at the moment.

<div class="cardBrand image">
  <img class="card-logo" title="Mastercard" src="/hosted/assets/payment-logo/mastercard-debit.png">
</div>

You can insert the title after the image like

 $('.cardBrand.image img').after(function() { return this.title; }).hide();
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="cardBrand image"> <img class="card-logo" title="Mastercard" src="/hosted/assets/payment-logo/mastercard-debit.png"> </div>

You can get the title of the image using $('#img-id').attr('title'); and then use it to set the html using $('#div-id').html($('#img-id').attr('title'));
You can use the class also.您也可以使用该类。 But, it will change all the div with the same class. It is recommended that you use an id for the div for these purposes

var image_title=$('.card-logo').attr('title'); // get title of image
$('.card-logo').hide(); // hide image
$('.cardBrand').text(image_title); // set title in parent div
var imgTitle="<span>" + $(".card-logo").attr("title") + "</span>";
$(imgTitle).insertAfter($(".card-logo"));
$(".card-logo").hide();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM