You really should use identifiers such as identifiers or classes, but for your example you can do this:
jQuery('div > div').bind('click', function() { jQuery(this).css('background','blue'); });
... which associates a handler with any div
that is a direct descendant of another div
.
Thus, either make your initial choice specific to the elements (s) you want to influence, or use delegation delegation, place a handler on the ancestor and check the element you want.
Delegation example: http://jsbin.com/ehemac/edit#javascript,live
<div id="container"> <div class="outer"> <div> text here </div> </div> <div class="outer"> <div> text here </div> </div> </div>
jQuery('#container').delegate( '.outer > div', 'click', function() { jQuery(this).css('background','blue'); });
The delegate()
[docs] method is used here, which places the handler on the ancestor with the identifier #container
.
The first argument to .delegate()
is a selector. Any elements pressed inside the #container
will have this selector compared to the pressed element. If the selector matches, a handler will be called.
source share