Creating an image element with src containing certain query string parameters

I would like to create an HTML image element like this one:

<img src="" />

I tried doing this:

var now = new Date().getTime();
var aid = 123456;
var sid = 78910;
var user = "abcd";

How can I create the element from this data?


  • You create an img element using document.createElement("img"). (A tag is an HTML text concept; when working with the DOM, you're working with elements and nodes and such.)

    You set its src, a string, using the src reflected property of that element. To create that string you'd use string concatenation (+) or a template literal (see below).

    So (string concatenation):

    const img = document.createElement("img");
    img.src = "" + aid +
                  "&param2=" + sid +
                  "&param3 = " + encodeURIComponent(user) +
                  "&param4=" + now;

    Or (template literal):

    const img = document.createElement("img");
    img.src = `${aid}&param2=${sid}&param3=${encodeURIComponent(user)}&param4=${now}`;

    Then you'd want to append that to the DOM somewhere (appendChild, append, insertBefore, etc.).

    Note the encodeURIComponent on the non-numeric one, user. Both the names and values in a query string must be URI-encoded. But I haven't bothered on param1, param2, etc. because they only have characters that don't need URI-encoding (same for numbers in normal form). But when in any doubt, encode, it won't do any harm even when unnecessary.

    Re your comment:

    And presumably if I'd like to add attributes to the img element it'd be like img.height=1 and img.width=1?

    The specification lists the properties of img elements (see the "DOM Interface"). Yes, both height and width are there and setting them has the same effect as using the height and width attributes, although you might want to use a stylesheet instead.

    Not all attributes have reflected properties. For those that don't, you'd use setAttribute("name", value) (the value will be converted to a string if it isn't already one).