I don't understand what I am doing wrong.
I have an element
<div >https://image.png</div>
I want to use juqery to loop through all the elements with .hello and then wrap it with the images tags so the image shows up.
For some reason jquery is spitting out the "Image URLhttps://image.png", as you see it has the "Image URL" text in there thats messing everything up!
Thanks
CodePudding user response:
Run this snippet .. The code in my comment works .. We loop through .each
class of hello
... Then we assign the element object to item
inside the loop. We grab the html
of item
(which contains the image path). We then rebuild the html
inside the class hello
with <img src ="">
$('.hello').each((index, item) => {
var img = $(item).html();
$(item).html('<img src="' img '">');
});
.hello_img{
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
https://files.porsche.com/filestore/image/multimedia/none/911-tu-modelimage-sideshot/model/fe21bac9-833c-11eb-80d3-005056bbdc38/porsche-model.png
</div>
<div >
https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Porsche_Panamera_4_E-Hybrid_(MSP17).jpg/1200px-Porsche_Panamera_4_E-Hybrid_(MSP17).jpg
</div>
CodePudding user response:
This ended up being very similar to Zak's code, but it uses jQuery's functions to manipulate the DOM rather than deconstructing and reconstructing HTML directly. This can prevent bugs that might arise when the div's contents include double-quotes, for example.
$('.hello').each((i, item) => {
const $item = $(item);
var url = $item.text();
$item.empty();
$item.append($('<img></img>').attr('src', url));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >https://upload.wikimedia.org/wikipedia/commons/8/8d/Frog_on_palm_frond.jpg</div>