# Selector targets overly obtuse - recommendations?

This presumably simple task resulted in much more scripting logic than I thought would be necessary.

Goal: when the user clicks a button inside one of the divs, it affects said div.

Issues: I did not wish to have my function target specific elements in my DOM. (ex. targeting <a> by ID). Also, because my function is traversing the DOM and being called in multiple instances, I had to use $(this) format so as not to be specific to one ID. Anyways, here is my code: $(".button").toggle(function(){
$(this).parent().children(".innerBox").fadeIn(); }, function(){$(this).parent().children(".innerBox").fadeOut();
});


It works fine. However, can someone with a little more jQuery savvy please let me how I could execute this function in the future, without having to parse through siblings and making it more convoluted than need be?

• You could simplify it some by doing: $(this).siblings(".innerBox")... – Shmiddty Oct 16 '12 at 21:18 • You could just use .toggleClass('on') / .toggleClass('off') and add transitions to your CSS for the fade effect. – Kevin Boucher Oct 16 '12 at 21:20 • @Kevin Boucher That wouldn't decrease the amount of code at all, but I see what you were thinking. The amount of code I'm writing doesn't need to be truncated by a CMS or something of the sort. I merely wanted a "better way of doing this". – Justin Ward Oct 16 '12 at 21:47 • @JustinWard, probably something like I answered is what you are looking for – Alexander Oct 16 '12 at 21:49 ## 2 Answers You can certainly cache the lookups, abusing of the scopes. $(".button").each(function(){
var $btn =$(this);
var $box =$btn.parent().children(".innerBox");
$btn.toggle(function(){$box.fadeIn();
}, function(){
$box.fadeOut(); }); });  Using .fadeToggle() instead of .fadeIn() and .fadeOut(). $(".button").each(function(){
var $btn =$(this);
var $box =$btn.parent().children(".innerBox");
$btn.click(function(){$box.fadeToggle();
});
});


And last but not least, .siblings().

$(".button").each(function(){ var$btn = $(this); var$box = $btn.siblings(".innerBox");$btn.click(function(){
$box.fadeToggle(); }); });  • Thanks, Alexander. .fadeToggle is nice! Good call. I too was creating variables, as I thought it might make things simpler, but it becomes a bit too confusing if others are intended to make sense of the code. Personal preferences, I guess. It's for that same reason I'm not a big fan of SASS (CSS) either. – Justin Ward Oct 16 '12 at 22:01 • @JustinWard, be advised, jQuery is a monster that you can't use without caching – Alexander Oct 16 '12 at 22:04 • Haha. Yeah, a bit of an oxymoron, eh? Using JQuery but not being a fan of variables...I just meant, I usually don't like creating even more variables. – Justin Ward Oct 16 '12 at 22:54 My only alteration would be $(this).parent().children(".innerBox")


\$(this).siblings(".innerBox")