Vecta Vecta - 4 months ago 7
jQuery Question

Resolve function not found errors on created DOM element

I'm working with JS and I'm a bit confused on something. When a user clicks an element I'd like to create an image element and animate it.

element = document.createElement("IMG");
element.src = "/path/to/file.jpg";
element.addClass("class1");


I receive the following error:


element.addClass is not a function


What am I doing wrong?

Answer

You're confusing DOM methods with jQuery methods. addClass is a jQuery method, but element is a DOM element, not a jQuery object.

If you want to stick to jQuery, the code would be:

var element = $("<img>", {
    src: "/path/to/file.jpg",
    "class": "class1"
});
Comments