views:

55071

answers:

6

I'm refactoring some old javascript and there's a lot of DOM manipulation going on.

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);

Is there a better way to do this using jQuery? I've been experimenting with:

 var odv = $.create("div");
 $.append(odv);

etc. But I'm not sure this is any better.

Google search gives me ambiguous answers on the subject. Clues?

+9  A: 

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.

Adam Bellaire
Maybe this was obvious, and indicated by your example, but creating a jQuery DOM element using the $("<html string>") syntax, cannot be appended into the DOM using the native <element>.appendChild method or similar. You must use the jQuery append method.
Adam
+55  A: 

here's your example in "one" line.

this.$OuterDiv = $('<div></div>')
    .hide()
    .append($('<table></table>')
        .attr({ cellSpacing : 0 })
        .addClass("text")
    )
;
nickf
You'll find that document.createElement is much faster than having jQuery convert your html string into an element. (just in case you have an urge to make things more efficient)
Sugendran
That's true for jQuery < 1.3 It's speed equivalent now I beleive.
Rob Stevenson-Leggett
You can reduce the above even further by creating elements like this: $('<div>') (without the closing tag). jQuery will add the closing tag.
Kevin Babcock
@Kevin, that is true, however it makes jQuery do more work (it runs it through a regex to add the closing tag), so I prefer the method above. Also, it differentiates your code from `$('div')` which is visually very similar, but functionally poles apart.
nickf
Kolky
@Kolky: Personally I'd prefer to forego the ~0.0001s speed improvement to have maintainable and easy-to-read code.
nickf
@Kolky, your code works, thanks.
jmoz
Also beware that jQuery will generate element tags that export in uppercase: http://stackoverflow.com/questions/2510702/why-is-nodename-sometimes-all-caps-in-javascript-dom/2510809#2510809
harpo
document.createElement('div') means more to me than $('<div></div>')
seanmonstar
I think the "correct" way is $('<div />'), with, IMO, has even more "meaning", since it's pretty obvious you are creating a Node. The bad thing is this way breaks the syntax highlighting in all editors =(
Erik Escobedo
A: 

jQuery out of the box doesn't have the equivalent of a createElement. In fact the majority of jQuery's work is done internally using innerHTML over pure DOM manipulation. As Adam mentioned above this is how you can achieve similar results.

There are also plugins available that make use of the DOM over innerHTML like appendDOM, DOMEC and FlyDOM just to name a few. Performance wise the native jquery is still the most performant (mainly becasue it uses innerHTML)

kouPhax
You should get up to date. jQuery does not use innerHtml but parses the HTML string and internally builds a DOM tree using document.createElement(). This is core jQuery.
Vincent Robert
You learn something new everyday. Thanks for the heads up.
kouPhax
+3  A: 

If you're creating a huge table, innerHTML and array.push is faster than the DOM methods. Especially in IE.

Mike Blandford
A: 

It's all pretty straight forward! Heres a couple quick examples...


var $example = $( XMLDocRoot );


var $element = $( $example[0].createElement('tag') ); // Note the [0], which is the root

$element.attr({ id: '1', hello: 'world' });


var $example.find('parent > child').append( $element );

Randy
+2  A: 

Creating new DOM elements is a core feature of the jQuery() method, see:

Cheers.

abernier