0

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

<img src="www.example.com?param1=aid&param2=sid&param3=user&param4=now" />

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?

2 Answers 2

6

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 = "http://www.example.com?param1=" + aid +
              "&param2=" + sid +
              "&param3 = " + encodeURIComponent(user) +
              "&param4=" + now;

Or (template literal):

const img = document.createElement("img");
img.src = `http://www.example.com?param1=${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).

Sign up to request clarification or add additional context in comments.

2 Comments

Good to know about the template string too. And that's just going to be JS no libraries or anything? Fantastic.
@DougFirr: Yup, once everyone upgrades their browsers, so ~2021 or so. :-) Meanwhile, transpilers like Babel already support it. Example
0

Strings in JS can be chained together with the + operator. Number values will be coerced to strings (although that sometimes won't work as expected).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.