Skip to content

Instantly share code, notes, and snippets.

@kellysutton
Created August 17, 2011 21:00
Show Gist options
  • Select an option

  • Save kellysutton/1152617 to your computer and use it in GitHub Desktop.

Select an option

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

mjc-gh commented Aug 26, 2011

Copy link
Copy Markdown

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
Copy Markdown
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

mjc-gh commented Aug 26, 2011 via email

Copy link
Copy Markdown

@danawoodman

Copy link
Copy Markdown

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
Copy Markdown

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