How to get the Image "title" attribute value into another element using jQuery

Viewed 63

I need to display the title value of the image (class name: media_image) in another p tag (class name: media_folder_title) for every row. But I can't able to get the value. I have attached the sample code here.

Screenshot:

enter image description here

HTML Code:

<div id="media-folder">
   <div class="media_folder">
      <i class="fa fa-folder-open"></i>
      <img src="/img/artist/default.jpg" alt="5382" title="Test" class="media_image">
      <p class="media_folder_title"></p>
   </div>
   <div class="media_folder">
      <i class="fa fa-folder-open"></i>
      <img src="/img/artist/default.jpg" alt="5383" title="test1" class="media_image">
      <p class="media_folder_title"></p>
   </div>
   <div class="media_folder">
      <i class="fa fa-folder-open"></i>
      <img src="/img/artist/default.jpg" alt="5118" title="Uploads" class="media_image">
      <p class="media_folder_title"></p>
   </div>
</div>

jQuery Code:

$(".media_folder img.media_image").each(function(){
    var imgtitle = $(this).attr("title");
    console.log(imgtitle);
    setTimeout(function(){
        console.log("settimout ok");
        $(this).append("<p>"+imgtitle+"</p>");
    }, 3000);
});
3 Answers

Change the selectors in the first line into:

.media_folder img .media_image

Sometimes space is important.

The problem is with the $(this) in the timeout because it's no longer the image but the window.

Also, append aims to append an element inside another element. It's not possible appending an element inside an image. As your snippet implies, you want to append the p tag after the image, after is the right function for that.

$(".media_folder img.media_image").each(function() {
  const $img = $(this);
  const imgtitle = $img.attr("title");

  setTimeout(function() {
    $img.after("<p>" + imgtitle + "</p>");
  }, 3000);
});
<div id="media-folder">
  <div class="media_folder">
    <i class="fa fa-folder-open"></i>
    <img src="/img/artist/default.jpg" alt="5382" title="Test" class="media_image">
    <p class="media_folder_title"></p>
  </div>
  <div class="media_folder">
    <i class="fa fa-folder-open"></i>
    <img src="/img/artist/default.jpg" alt="5383" title="test1" class="media_image">
    <p class="media_folder_title"></p>
  </div>
  <div class="media_folder">
    <i class="fa fa-folder-open"></i>
    <img src="/img/artist/default.jpg" alt="5118" title="Uploads" class="media_image">
    <p class="media_folder_title"></p>
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Your problem is that you are trying to append something inside an img tag, which is not possible - as with a few other html elements.

What you are looking for is $.after()

Try $(this).after($('<p />').text(imgtitle))

Related