Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

JQuery document.createElement equivalent?

I'm refactoring a few old javascript code and there may be lots of DOM manipulation happening.
var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;

var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);

I would really like to know if there may be a better manner to do that the use of jquery. I have been experimenting with:

var odv = $.create("div");
$.append(odv);
// And many more

However, I don't know whether this is any better.
by

2 Answers

ninja01
Simply supplying the HTML of elements you want to add to a jQuery constructor $() will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's append() method.

For example:

var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);

You could then populate this table programmatically, if you wished.

This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using createElement and then setting attributes like cellSpacing and className via JS.
kshitijrana14
I'm doing like that:
$('<div/>',{
text: 'Div text',
class: 'className'
}).appendTo('#parentDiv');

Login / Signup to Answer the Question.