qua1ity qua1ity - 1 month ago 5
Javascript Question

Add attributes directly within an append

Can you add attributes to an element within an append, something like this:

var video = $("<video>").append("<source>", {
src: 'https://www.youtube.com/',
width: 100,
height: 200
});


I'm asking because I think I have seen something like this before, but can't quite remember how it was written. I know you can do this with jQuery and attr(), but I'm looking for a way without using attr() or similar methods.

I think it was written with jQuery, but might have been something like underscorejs aswell, I'm not sure. Anyone know?

Answer

You're close, but missing the jQuery wrapper when creating the child element:

var video = $("<video>").append($("<source />", {
  src: 'https://www.youtube.com/', 
  width: 100, 
  height: 200
}));