YakovL YakovL - 1 year ago 67
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
element with the class but without
attribute. If I then use this:


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

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


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download