Every now and then, I have a need to target a specific text widget or image widget in a WordPress sidebar. For example, I have a site that uses a text widget to display some html code at the top of the sidebar and I need to give it a certain background color.

By default, WordPress gives each text widget its own id, but the problem is that if you accidentally delete the widget, the id will change. So, targeting by id is out.

There are a couple of other ways to target the widget. I could use CSS pseudo selectors like “first-child” and “nth-child”, but, of course, then I run into IE8 issues with my behind-the-times friends.

So, I use jQuery’s eq() method.

Here is how the code looks:

$('#myID .text-widget').eq(0).addClass('first-child-of-myID');
$('#myID .text-widget').eq(1).addClass('second-child-of-myID');

Pretty slick!

I know that you CSS purists are cringing, and that’s okay. 😉