Tuesday, January 8, 2019

Find This Not That in jQuery

Today at work, I came across a jQuery find statement that was selecting a bunch of different elements but I needed to excluded a single class from the selection. Of course, I hit Google and Stack Overflow for an answer but nothing was quite exactly what I needed. I found the solution and also learned something else about jQuery in the process. So here is what I came up with.

The solution was to chain a filter call to the find statement using the not selector.

Here is a contrived example on CodePen. In this example, I am selecting all buttons except for the btn-danger and btn-warning classes:
var myButtons = $('#main')
     .find('button')
     .filter(':not(".btn-danger,.btn-warning")');

Something I noticed in the console is that there is an object created called prevObject. This object contains the matched elements before the filter is applied which could be useful.

0 comments:

Post a Comment

 
Blogger Templates