Skip to content

Instantly share code, notes, and snippets.

@kellysutton
Created August 17, 2011 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellysutton/1152617 to your computer and use it in GitHub Desktop.
Save kellysutton/1152617 to your computer and use it in GitHub Desktop.
Use jQuery for element construction
var createMyWrappedInput = function (defaultValue) {
var wrapper = $("<div class='Wrapper'></div>"),
input = $('<input type="text" />');
input.val(defaultValue);
wrapper.append(input);
return wrapper;
};
@mjc-gh
Copy link

mjc-gh commented Aug 26, 2011

why not do:

var wrapper = $('<div>', {'class': 'Wrapper'}),
    input = $('<input>', {type: 'text'});

to make it even more "jQuery-ish", increase readability and avoid potentially issues with quotes.

@kellysutton
Copy link
Author

Never even knew you could do that. I'll play around with it and possibly update the gist. Thanks for the suggestion!

@mjc-gh
Copy link

mjc-gh commented Aug 26, 2011 via email

@danawoodman
Copy link

Changing your variable names from wrapper and input to $wrapper and $input will let you know the variable contains a jQuery object. Especially useful in larger functions/more complicated code.

@danawoodman
Copy link

One other note: If you're finding yourself using lots of concatenation or appending, try using jQuery-tmpl which allows you to create HTML templates that you can populate with data (similar to Django templates).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment