jQuery HTML5 :dataAttr Pseudo Selector

Problem

A while back someone on twitter was asking me how they might find a set of DOM elements by using doing a partial search on their HTML5 data attribute.

I'm not actually sure what type of use case you would need for such problem, but I thought it was an interesting issue to work on, so I went ahead and took a stab at solving it.

Desired Solution

In order to solve the above example of finding elements that start with a certain HTML5 data attribute, I wanted to follow a similar API to that of jQuery Attribute Selectors with the ^=, $=, etc… syntax. The following is an example of how I thought the solution should look like.

Custom Pseudo Selector

In order to create an API like the above I needed to create a custom pseudo selector, much like what you’ve seen when using :last, :odd, :eq( number ), and numerous other common selectors.

Unit Tests

I didn’t want to just have some code laying around that wasn’t thoroughly tested, so I went ahead and created a set of unit tests to cover various scenarios. I could have kept going, but I thought the following was a decent set of tests to start with.

If you enjoyed this post, please consider sharing it with others via the following Twitter or Reddit buttons. Also, feel free to checkout my egghead.io profile page for addition free and subscription lessons, collections, and courses. As always, you can reach out to me on Twitter at @elijahmanor. Thanks and have a blessed day!

Reddit