Skip to content

Instantly share code, notes, and snippets.

@rchowe
Created January 20, 2012 16:34
Show Gist options
  • Save rchowe/1648287 to your computer and use it in GitHub Desktop.
Save rchowe/1648287 to your computer and use it in GitHub Desktop.
Selector-based create for jquery
# Creates an element based on a selector.
# Currently only works for tag, id, and class.
$.fn.create = (selector) ->
# Process the selector string if necessary
if typeof selector is 'string'
# Convenience
class Selector
constructor: (@tag, @id, @classes, @child)
reverse_call = (object, method, args...) ->
args.reverse()
object[method].apply object, args
# Validate the selector
unless selector.match /^(?:\w+|#\w+|\.\w+)+(?: (?:\w+|#\w+|\.\w+)+)*$/
throw 'Invalid selector'
# Separate into components
elements = selector.
trim().
split( ' ' ).
map( (x) => x.split /(?=[#.])/ ).
reverse()
# Reduce to an object chain
selector = reverse_call elements, 'reduce', null, (child, element) =>
# Convenience function to tell type
type = (x) => {'#': 'id', '.': 'class'}[x[0]] or 'tag'
# Tag
[tag, rest...] = element.filter (x) => (type x) is 'tag'
if rest? and rest.length > 0
throw 'Multiple tags found in selector'
# ID
[id, rest...] = element.
filter( (x) => (type x) is 'id' ).
map( (x) => x.slice 1 )
if rest? and rest.length > 0
throw 'Multiple IDs found in selector'
# Classes
classes = element.
filter( (x) => (type x) is 'class').
map( (x) => x.slice 1)
# End result
new Selector tag, id, classes, child
# Create the element(s)
element = document.createElement selector.tag or 'div'
element.id = selector.id if selector.id?
if selector.classes?
if selector.classes.length == 1
element.className = selector.classes[0]
else
element.className = selector.classes.join '.'
# Append the element
this.append element
# Recurse
$(element).create selector.child if selector.child?
# Return
$(element)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment