Replicating the deprecated jQuery property .selector in CoffeeScript

Recently I found myself needing a way to get any (id or class) selector from any DOM element as a string in an easy way. 

After a quick search I discovered that jQuery had an handy .selector property that would have been a perfect fit for my needs.

Unluckily, it was deprecated in version 1.7.

image

I felt like the solution suggested by the guys at jQuery wasn’t flexible enough and not very user-friendly – passing the element selector as a parameter of the plugin method call is definitely not an elegant way to deal with the problem.

So I tried to write a simple function to solve it… in CoffeeScript!

The snippet

getSelector = (el) ->
  firstClass = $(el).attr('class')?.split(' ')[0]
  elId       = $(el).attr('id')

  if (elId isnt undefined) then "##{elId}" else ".#{firstClass}"

As you can see, it’s really easy to understand: it just checks if there’s an id attribute and returns it as a string. If it’s undefined, it returns the first class instead.

Here you can see it in action in a CodePen example.

I could write it in a single line without the two variables declaration, but I wanted to get the most out of the beautiful human-friendly CoffeeScript syntax, and I think it actually makes the snippet a lot more readable.

More jQuery pls

If you wanted to, you could also extend jQuery itself adding this little function as a method in a very easy way:

jQuery.fn.extend(
  getSelector: ->
    firstClass = $(this).attr('class')?.split(' ')[0]
    elId       = $(this).attr('id')

    if (elId isnt undefined) then "##{elId}" else ".#{firstClass}"
)

And then use it like that:


$ ->
  mySelector = $('div').getSelector()

Hope that helped you!

Leave a Reply

wpDiscuz