How to Target a Specific Text Widget with CSS + jQuery

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');

[source]

Pretty slick!

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

Posted in

Toby Cryns

Toby Cryns is a freelance CTO, expert WordPress consultant, and teacher.

He offers free advice to improve your freelance biz.

He also publishes small droppings every now and then to twitter.com/tobycryns and twitter.com/themightymo

Follow Toby's contributions on Github and WP.org.