YakovL YakovL - 1 month ago 8
Javascript Question

Why does jQuery('<img class="pull-left"/>', { src: '...' }) create an image without src?

The issue is that I try to create an image using the following code:

var $img = jQuery('<img class="pull-left"/>', {
src: 'images/video.svg'
})


Surprisingly, it only creates an
img
element with the class but without
src
attribute. If I then use this:

$img.attr('src','images/video.svg');


The image then gets its
src
attribute. Why is that? Here's a simple snippet that illustrates the issue:



$img = jQuery('<img class="pull-left"/>',{
src: 'images/video.svg'
});
alert($img.attr('src'));

$img.attr('src','images/video.svg');
alert($img.attr('src'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>




Answer

The official documentation for jQuery( html, attributes ) says that the first parameter should be a string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).

So either remove the class and add it to the parameters objects, or use attr:

$img = jQuery('<img/>',{
    src: 'images/video.svg',
    class: 'pull-left'
});

-- OR --

var $img = jQuery('<img class="pull-left"/>');
$img.attr('src', 'images/video.svg');

The second approach is suited for situations when you create and modify the element in different parts of your code.