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:
HTML Code:
<div id="media-folder">
<div >
<i ></i>
<img src="/img/artist/default.jpg" alt="5382" title="Test" >
<p ></p>
</div>
<div >
<i ></i>
<img src="/img/artist/default.jpg" alt="5383" title="test1" >
<p ></p>
</div>
<div >
<i ></i>
<img src="/img/artist/default.jpg" alt="5118" title="Uploads" >
<p ></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);
});
CodePudding user response:
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 >
<i ></i>
<img src="/img/artist/default.jpg" alt="5382" title="Test" >
<p ></p>
</div>
<div >
<i ></i>
<img src="/img/artist/default.jpg" alt="5383" title="test1" >
<p ></p>
</div>
<div >
<i ></i>
<img src="/img/artist/default.jpg" alt="5118" title="Uploads" >
<p ></p>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
CodePudding user response:
Change the selectors in the first line into:
.media_folder img .media_image
Sometimes space is important.
CodePudding user response:
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))

