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. I also have a YouTube Channel with free web development videos that you are welcome to watch and/or subscribe. As always, you can reach out to me on Twitter at @elijahmanor. Thanks and have a blessed day!

Reddit