jQuery: How can I target a specific tag, such as UL?

Tuesday, July 17th, 2012 | Business | by

jQueryjQuery is a flexible javascript framework that lets you do a lot.  One major component of jQuery is the concept of the “selector“.

If you want to apply some jQuery code to an item, you use it’s selector.  For example to turn on a class for all anchor tags (A) you use:

$(“a“).toggleClass(“className”, true);

The “a” in bold is the “selector”.  In this case we told jquery (which is “$”) to select all anchor tags.  We then said, “with what is selected, toggle the className class on”.

If you only wanted to do that for anchor tags with the class “nav” (<a class=’nav’>) you would use:

$(“a.nav“).toggleClass(“className”, true);

Frequently WordPress uses an unordered list (UL) to denote the primary navigation with the class “menu”.  If we wanted to turn on an “activeMenu” class only for this UL, we would do:

$(“ul.menu“).toggleClass(“activeMenu”, true);

While classes are helpful in targeting a jQuery selector, they are less efficient than using an exact ID.  WordPress (I work in WP a lot) uses the ID “menu-menu” in it’s twenty eleven theme.  The UL tag in WordPress for the primary nav is:

<ul id=”menu-menu” class=”menu”>

If we only wanted to target that UL, it would be best to specify the ID using a jQuery selector:

$(“#menu-menu“).toggleClass(“activeMenu”, true);

See the “#menu-menu” selector used?  It says find the element who’s ID is “menu-menu” and toggle the class “activeMenu” on.

Tons more to learn, so read through the jQuery selectors page for more information.  If you have any questions, post them below.


Related Posts

Tags: , , , , , ,

No comments yet.

Leave a comment


Please share, it makes me happy:

Subscribe to Email Alerts

Follow Me

Follow seangw on twitter



prestashop theme

virtuemart template