2

Instead of this code:

let img = document.createElement("img");
img.src = "foo.png";
img.className = "bar";
img.id = "abc123";

I'd like to do something like this:

let img = document.createElement("img")
{
    src = "foo.png";
    className = "bar";
    id = "abc123";
}

I know I could write a function or a constructor to do it, but just wondering if there is some sort of native support for that in TypeScript?

Charles Clayton
  • 17,005
  • 11
  • 87
  • 120

2 Answers2

1

Yes there is, in a sense..

export class newImgModel{
   src: string = "foo.png";
   className:string = "bar";
   id: string = "abc123";
}

So you can create an element like so :

Create a class to handle it :

class Dynamically_create_element
{
    thingToAdd:newImgModel;
    Create_Element(thingToAdd)
    {
    var element = document.createElement("img");
    //Assign different attributes to the element.
    element.setAttribute("src", thingToAdd.src);
    element.setAttribute("class",thingToAdd.className);
    element.setAttribute("id", thingToAdd.id);
    document.body.appendChild(element);
    }

}

Then you can use like so :

var objToAdd = new newImgModel();
var create = new Dynamically_create_element();
create.Create_Element(objToAdd );

That should do the trick.. But I haven't tested!

Reference : CS-Corner

Pogrindis
  • 7,755
  • 5
  • 31
  • 44
  • This does a bit too much work to create an image. You'd have to create and export a new class for each image, which can't be done dynamically, and it doesn't use an options object. – mk. Dec 10 '15 at 18:54
1

There is no native support for this in TypeScript. The built-in HTMLImageElement interface is not suitable for this use as an options object since it has no optionals. The reason there is no native support in TypeScript is because there's really no native support for this in JavaScript. You can't pass in options objects during element creation.

Writing this yourself is straightforward, though:

export interface CreateImgOptions {
    src: string;
    className?: string;
    id?: string;
}

export function createImg(options: CreateImgOptions): HTMLImageElement {
    let img = <HTMLImageElement> document.createElement("img")
    img.src = options.src;
    if (options.className) img.className = options.className;
    if (options.id) img.id = options.id;
    return img;
}

Usage:

let img = createImg({
    src: "foo.png",
    className: "bar",
    id: "abc123"
});
let img2 = createImg({src: "foo2.png"});
mk.
  • 11,360
  • 6
  • 40
  • 54