How to create and add image using javascript / jQuery?

I use the following code to create an image element, load it, and then add it to the article when loading.

$('<img />') .attr('src', 'image.png') //actually imageData[0].url .load(function () { $('article').append($(this)); alert('image added'); }); 

The warning turns off normally, but the image does not appear, and when I check the item, it was added without a closing slash

 <img src='image.png' > 

Why does the browser remove the slash and how to stop it?

UPDATE : Thanks to everyone who pointed out that this is not a slash, that there is a problem (every day is a school day), so what could it be? Here is a live example http://chris-armstrong.com/inspiration/?username=behoff

UPDATE 2 : So, I seem like an idiot not to test this with other images, as the problem seems to be related to the test image I used ( http://img.ffffound.com/static-data/assets/6/ dc01f803819405bfe160459021cfe6cc57766f9b_m.jpg ). Strange, because it loads when you click on the URL ... but anyway, thanks to all your helpers, I found out something!

+4
source share
3 answers

Based on the information provided, we know the following:

  • Image added successfully.

  • The image was uploaded successfully (otherwise you will not receive alert() ).

Either you have a completely transparent image (unlikely, of course), or I would argue that your CSS somehow interferes with its display.

Here is an example of using CSS that you commented out in your demo.

http://jsfiddle.net/JxhaR/ (No visible image)

In particular, crime is as follows:

 display: -webkit-box; 

When I turn this off, an image will be displayed.

http://jsfiddle.net/JxhaR/1/ (Image visible.)

+3
source

Try the following:

 $('<img />') .attr('src', 'image.png') .append('article') .load(function(){ alert('image added'); }); 
+1
source

When you check an item, you do not see it as it was added. Regardless of whether the elements are added as HTML code or as elements (as in this case), when you check the code you are looking for, the code created from this element, you do not look at the code that was used to add the element.

When you use $('<img />') , document.createElement('img') actually does this, so there is no HTML where the trailing slash may or may not be present. An element is created as a DOM object; it is not created from HTML code.

Thus, the reason the image does not appear is not because the tag does not have a trailing slash.

The likely reason is that the image does not actually exist where the browser is looking for it, i.e. missing file or url is invalid.

+1
source

Source: https://habr.com/ru/post/1340448/


All Articles