Last Updated: February 25, 2016
·
4.841K
· sir_ov

Create DOM elements with jQuery

Well this is the way I create DOM elements using jQuery or blocks of html code, for example to the append or prepend function, that's the most casual case I have seen and people write all the HTML in JS variables instead of write fewer lines and a beautiful code.

Example:

/* Creating an <img> element */
var $img = '<img src="lalala.xxx" width="350" height="250" />';

/* Instead of do that ^, try this */
var $img = $('<img>', { width : 350, height : 250, src : 'lalala.xxx' });

You can create any DOM element with this code, first param the tag, second parameter a JSON with the features.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside